BITCOUNT
BITCOUNT key [start end [BYTE | BIT]]
- Group
- Bitmap
- Complexity
- O(N) where N is the size of the range
- Arity
- -2 (at least 2 words, counting the command name)
- Flags
- read-only
- Keys
- first 1, last 1, step 1
- HotKV Cloud
- All plans
- On-Premise
- no license needed
BITCOUNT counts the bits set to 1 in the string at key. Without a range
it counts the whole string. With start and end it counts only that range,
both ends included; negative values count back from the end of the string. By
default the range is in bytes; add BIT to give it in bits. A missing key
counts as 0.
Options
Section titled “Options”| Option | Effect |
|---|---|
start end |
Count only this range. Both must be given together. |
BYTE |
start and end are byte offsets (the default). |
BIT |
start and end are bit offsets. |
Return value
Section titled “Return value”| Case | RESP2 | RESP3 |
|---|---|---|
| Always | Integer: the number of set bits | Integer |
Errors:
ERR syntax errorfor astartwithout anend, or a unit other thanBYTEorBIT.ERR value is not an integer or out of rangewhenstartorendis not an integer.WRONGTYPEwhen the key holds a value that is not a string.
Examples
Section titled “Examples”127.0.0.1:6379> SET mask "hi"OK127.0.0.1:6379> BITCOUNT mask(integer) 7127.0.0.1:6379> BITCOUNT mask 0 0(integer) 3127.0.0.1:6379> BITCOUNT mask 5 10 BIT(integer) 2Compatibility
Section titled “Compatibility”Same as Redis 7 and Valkey 8.
See also
Section titled “See also”Was this page helpful?
Thanks for the feedback.