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:

uint8_t x = 0b00000000; // initial byte 

void setup() {
  Serial.begin(9600);
  
  int index = 6; // index of the bit to modify
  
  x |= bit(index-1);

  Serial.print("The resulting byte is: ");
  Serial.println(x, BIN);
 
}

void loop() {
}

Note

This is what the bit() function does behind the scenes:

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

See also