Reputation: 134
127.0.0.1:6379> setbit mykey 1 1
(integer) 0
127.0.0.1:6379> setbit mykey 23 1
(integer) 0
127.0.0.1:6379> setbit mykey 345 1
(integer) 0
127.0.0.1:6379> get mykey
"@\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@"
127.0.0.1:6379>
I want to parse the above output string ( as a string of bits, like "100000000011...") to get the indexes of the set bits, how would I do it?
Upvotes: 2
Views: 1212
Reputation: 4677
You know the setbit
is just set the bit of a string, so the mykey
is holding a string. when you use the command get mykey
, it just return the string value.
And the \x00
is a also a char, you could refer this ASCII TAble.
Every char has eight bits, and the bitmap is just composed of all bits of every char of the string. its order is that every 8 bits's order is char's order in string, and in this every 8 bits, the order of bit is from the high bit to low bit. for example, if the string is @\x00
, then the length of string is 2, the bits length is 16. The ascii value of @
is 64 in decimal, and the ascii of \x00
is 0.
So its bitmap is :
0100 0000 0000 0000
So their offsets is from 0 to 15 from the left to right.
If you have a doubt about this, you could execute this commands in redis-cli to test:
setbit test 1 1
setbit test 15 0
get test
It will be @\x00
.
So the relation between the bitmap and string is clear, we could use the string to get the bitmap we want.
just use a simple python script:
s = "@\x00"
bitmap = ""
for c in s:
x = ord(c)
str = bin(x).split('b')[1]
if len(str) < 8 :
str = '0' * (8-len(str)) + str
bitmap += str
print bitmap
In this script , it uses the ord
to get ascii value of char, and use to bin to convert the dec to bin, and add 0 to high bit it length is smaller than 8
the output is :
0100000000000000
Upvotes: 5