# BITCOUNT

> Count the set bits in a string, optionally within a byte or bit range.

URL: https://docs.hotkv.com/commands/bitcount/

```
BITCOUNT key [start end [BYTE | BIT]]
```

- Group: Bitmap
- Complexity: O(N) where N is the size of the range
- 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

| 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

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Always | Integer: the number of set bits | Integer |

Errors:

- `ERR syntax error` for a `start` without an `end`, or a unit other than
  `BYTE` or `BIT`.
- `ERR value is not an integer or out of range` when `start` or `end` is not
  an integer.
- `WRONGTYPE` when the key holds a value that is not a string.

## Examples

```
127.0.0.1:6379> SET mask "hi"
OK
127.0.0.1:6379> BITCOUNT mask
(integer) 7
127.0.0.1:6379> BITCOUNT mask 0 0
(integer) 3
127.0.0.1:6379> BITCOUNT mask 5 10 BIT
(integer) 2
```

## Compatibility

Same as Redis 7 and Valkey 8.

## See also

[BITPOS](https://docs.hotkv.com/commands/bitpos/index.md), [SETBIT](https://docs.hotkv.com/commands/setbit/index.md),
[BITOP](https://docs.hotkv.com/commands/bitop/index.md)