> setbit mykey 1 1
> setbit mykey 7 1
When I store string value 1 and 7 into "mykey", what was exactly stored in redis? And how the getbit works inside redis?
Does anyone try to loop the bit inside this value? I know bitcount will give me number 2, but I also want to get the exact string value 1 and 7 from it, is it possible?
--
I doing some experiment by using erlang redis client to read the output.
> setbit mykey 1 1
erlang output:
<<"@">>
Then I delete this entry:
> del mykey
I do the same thing to offset 2 4 8, here you can see the mapping:
When offset is 1, the output is <<"@">>;
When offset is 2, the output is <<" ">>;
When offset is 4, the output is <<"\b">>;
When offset is 8, the output is <<0,128>>;
Honestly, I am more confused now.
Or someone can explain this "bitops.c"
-- updates ---
Maybe I should mention the reason why I want to do this to make the question more clear. We all know it will be cool to use bitmap to store online users. What I am trying to do is get the exactly user id who is online from what redis stored.
Just finished a quick version to extract offsets from redis. Please feel free to improve it.
u can see the exactly details in http://redis.io
GETBIT key offset
Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also assumed to be a contiguous space with 0 bits.
examples:
As its name implies,
SETBIT
allows you to perform bit operations - namely set a given bit to 0 or 1, at a given bit offset, for a given key.What is important to understand is that the result not always includes only printable characters. This is why Redis uses a custom function
sdscatrepr
to format the CLI output:That being said let's start with a simple example. If you consider the hex number
0x7F
(= 127) its binary representation on 8-bit is:You can typically use
SETBIT
to store this value, keeping in mind that offset0
isMSB
and offset 7 isLSB
:The get your value to inspect if:
Now what happens with multi bytes? Let's say you want to store
0x52
(= 82) which corresponds to characterR
in ASCII. The 8-bit representation is01010010
with bit positions(8, 9, ..., 15)
since we want it to be stored right after the first value:And you get:
Here Redis CLI is able to represent the printable character
R
.It corresponds to
01000001
which is equal to 65 and0x41
in hex. It corresponds to ASCII characterA
. So doing:Gives:
It simply returns the value of the bit at the given position. Here:
But bit 0 has not been set (it is 0 by default) thus: