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:
Append to the sds string "s" an escaped string representation where all the non-printable characters (tested with isprint()) are turned into escapes in the form "
a...." or "x".
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:
pos: 0 1 2 3 4 5 6 7
bit: 0 1 1 1 1 1 1 1
^ ^
| |
MSB LSB
You can typically use SETBIT
to store this value, keeping in mind that offset 0
is MSB
and offset 7 is LSB
:
redis> SETBIT myval 0 0
(integer) 0
redis> SETBIT myval 1 1
(integer) 0
redis> SETBIT myval 2 1
(integer) 0
redis> SETBIT myval 3 1
(integer) 0
redis> SETBIT myval 4 1
(integer) 0
redis> SETBIT myval 5 1
(integer) 0
redis> SETBIT myval 6 1
(integer) 0
redis> SETBIT myval 7 1
(integer) 0
The get your value to inspect if:
redis> GET myval
"x7f"
Now what happens with multi bytes? Let's say you want to store 0x52
(= 82) which corresponds to character R
in ASCII. The 8-bit representation is 01010010
with bit positions (8, 9, ..., 15)
since we want it to be stored right after the first value:
redis> SETBIT myval 8 0
(integer) 0
redis> SETBIT myval 9 1
(integer) 0
redis> SETBIT myval 10 0
(integer) 0
redis> SETBIT myval 11 1
(integer) 0
redis> SETBIT myval 12 0
(integer) 0
redis> SETBIT myval 13 0
(integer) 0
redis> SETBIT myval 14 1
(integer) 0
redis> SETBIT myval 15 0
(integer) 0
And you get:
redis> GET myval
"x7fR"
Here Redis CLI is able to represent the printable character R
.
When I store string value 1 and 7 into "mykey"
It corresponds to 01000001
which is equal to 65 and 0x41
in hex. It corresponds to ASCII character A
. So doing:
redis> SETBIT mykey 1 1
(integer) 0
redis> SETBIT mykey 7 1
(integer) 0
Gives:
redis> GET mykey
"A"
how the getbit works inside redis?
It simply returns the value of the bit at the given position. Here:
redis> GETBIT mykey 1
(integer) 1
But bit 0 has not been set (it is 0 by default) thus:
redis> GETBIT mykey 0
(integer) 0