# SETBIT

> Set or clear one bit of the string stored at a key.

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

```
SETBIT key offset value
```

- Group: Bitmap
- Complexity: O(1)
- HotKV Cloud: all plans
- On-Premise: no license needed

`SETBIT` sets the bit at `offset` in the string at `key` to `value` (`0` or
`1`) and returns the bit's previous value. Bit 0 is the most significant bit
of the first byte. When the string is too short it grows, padded with zero
bytes; a missing key is created. The key keeps its time to live.

`offset` must be at least 0 and below the number of bits in the largest
allowed string (`proto-max-bulk-len`, 512 MB by default, which is 2^32 bits).
Setting a high bit on a new or short key allocates the whole string up to that
bit at once.

## Return value

| Case | RESP2 | RESP3 |
| --- | --- | --- |
| Always | Integer: the previous value of the bit, `0` or `1` | Integer |

Errors:

- `ERR bit offset is not an integer or out of range` for a bad `offset`.
- `ERR bit is not an integer or out of range` when `value` is not `0` or `1`.
- `WRONGTYPE` when the key holds a value that is not a string.

## Examples

```
127.0.0.1:6379> SETBIT flags 7 1
(integer) 0
127.0.0.1:6379> SETBIT flags 7 1
(integer) 1
127.0.0.1:6379> GET flags
"\x01"
127.0.0.1:6379> GETBIT flags 7
(integer) 1
```

## Compatibility

Same as Redis 7 and Valkey 8.

## See also

[GETBIT](https://docs.hotkv.com/commands/getbit/index.md), [BITCOUNT](https://docs.hotkv.com/commands/bitcount/index.md),
[BITFIELD](https://docs.hotkv.com/commands/bitfield/index.md), [BITPOS](https://docs.hotkv.com/commands/bitpos/index.md)