# BITPOS

> Find the position of the first bit set to 0 or 1 in a string.

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

```
BITPOS key bit [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

`BITPOS` returns the position of the first bit equal to `bit` (`0` or `1`) in
the string at `key`. The position is always counted from the start of the
string, in bits, even when you search a range. `start` and `end` limit the
search; negative values count back from the end, and by default they are byte
offsets (add `BIT` for bit offsets).

When looking for a `0` bit without an `end`, the string is treated as if it
continued with zero bits, so a string with every bit set returns the first
position after its end. With an explicit `end`, a range without the bit
returns `-1`. A missing key returns `0` when looking for `0` and `-1` when
looking for `1`.

## Options

| Option | Effect |
| --- | --- |
| `start` | Begin the search at this offset. |
| `end` | Stop the search at this offset, included. |
| `BYTE` | `start` and `end` are byte offsets (the default). |
| `BIT` | `start` and `end` are bit offsets. |

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Found | Integer: the bit position | Integer |
| Not found | Integer `-1` (or the position after the end, see above) | Integer |

Errors:

- `ERR bit is not an integer or out of range` when `bit` is not `0` or `1`.
- `ERR value is not an integer or out of range` when `start` or `end` is not
  an integer.
- `ERR syntax error` for a unit other than `BYTE` or `BIT`.
- `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> BITPOS mask 1
(integer) 1
127.0.0.1:6379> BITPOS mask 1 1
(integer) 9
127.0.0.1:6379> BITPOS mask 1 7 15 BIT
(integer) 9
127.0.0.1:6379> SET full "\xff"
OK
127.0.0.1:6379> BITPOS full 0
(integer) 8
127.0.0.1:6379> BITPOS full 0 0 0
(integer) -1
```

## Compatibility

Same results as Redis 7 and Valkey 8. With more than six arguments HotKV
replies with `ERR wrong number of arguments for 'bitpos' command`, where Redis
replies `ERR syntax error`.

## See also

[BITCOUNT](https://docs.hotkv.com/commands/bitcount/index.md), [GETBIT](https://docs.hotkv.com/commands/getbit/index.md),
[SETBIT](https://docs.hotkv.com/commands/setbit/index.md)