bit()

Description

Create a bitmask with a single bit set at a specific position. Useful for bitwise operations, like setting, clearing, or testing specific bits in a byte or register.

Syntax

Use the following function to set the bit state on the

n
position:

bit(n)

Parameters

The function admits the following parameter:

n
: the bit position whose value to compute. Note that
n
needs to be between 0-31 (32 bit). Position 0 is the least-significant (rightmost) bit.

Returns

The function returns an unsigned byte (aka uint8_t) with only bit n set to

1
, and all others set to
0
.

Example Code

Modify a given byte

x
by turning its 6th bit to
1
:

1uint8_t x = 0b00000000; // initial byte
2
3void setup() {
4 Serial.begin(9600);
5
6 int index = 6; // index of the bit to modify
7
8 x |= bit(index-1);
9
10 Serial.print("The resulting byte is: ");
11 Serial.println(x, BIN);
12
13}
14
15void loop() {
16}

Note

This is what the

bit()
function does behind the scenes:

1#define bit(n) (1 << (n))

See also

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.