Description

Clears (writes a 0 to) a bit of a numeric variable at a specific position. Useful when you're doing low-level bit manipulation, especially when working with hardware registers, flags, or memory-mapped I/O.

Syntax

Use the following function to clear the bit state on the n position of the x variable:

bitClear(x, n)

Parameters

The function admits the following parameters:

  • x: the numeric variable whose bit to clear.
  • n: which bit to clear, starting at 0 for the least-significant (rightmost) bit.

Returns

The function returns the value of the numeric variable after the bit at position n is cleared.

Example Code

Modify a given byte x by turning its 6th bit to 0:

uint8_t x = 0b11111111; // initial byte 

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

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

void loop() {
}

Note

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

#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))

See also