BITPOS
Return the position of the first bit set to 1 or 0 in a string.
The position is returned, thinking of the string as an array of bits from left to right, where the first byte’s most significant bit is at position 0, the second byte’s most significant bit is at position 8, and so forth.
The same bit position convention is followed by and SETBIT
.
You can use the optional BIT
modifier to specify that the range should be interpreted as a range of bits. So start=0
and end=2
means to look at the first three bits.
Note that bit positions are returned always as absolute values starting from bit zero even when start and end are used to specify a range.
Like for the GETRANGE
command start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, -2 is the penultimate, and so forth. When BIT
is specified, -1 is the last bit, -2 is the penultimate, and so forth.
Integer reply: the command returns the position of the first bit set to 1 or 0 according to the request.
If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned.
If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns the first bit not part of the string on the right. So if the string is three bytes set to the value the command BITPOS key 0
will return 24, since up to bit 23 all the bits are 1.
However, this behavior changes if you are looking for clear bits and specify a range with both start and end. If no clear bit is found in the specified range, the function returns -1 as the user specified a clear range and there are no 0 bits in that range.
dragonfly> SET mykey "\xff\xf0\x00"
"OK"
dragonfly> BITPOS mykey 0
(integer) 12
"OK"
dragonfly> BITPOS mykey 1 0
dragonfly> BITPOS mykey 1 2
(integer) 16
dragonfly> SET mykey "\x00\x00\x00"
"OK"
(integer) -1
dragonfly> SET mykey "\x00\x00"
"OK"
(integer) 8