Arduino Setting or Clearing a Bit by Variable Position
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about Arduino Setting or Clearing a Bit by Variable Position. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Setting or clearing a bit using a variable bit position does not work as expected.
Quick Fix
Wrong
int bitPos = 3;
flags = flags | (1 << bitPos); // Works, but may overflow if bitPos > 15
Overflow if bitPos >= 16 on AVR's 16-bit int.
Right
int bitPos = 3;
uint32_t flags = 0;
// Set bit at variable position
flags |= ((uint32_t)1 << bitPos);
// Clear bit at variable position
flags &= ~((uint32_t)1 << bitPos);
// Toggle bit at variable position
flags ^= ((uint32_t)1 << bitPos);
Serial.print("Flags: 0x");
Serial.println(flags, HEX);
Flags: 0x8 (setting bit 3 on a 32-bit variable).
Prevention
Cast 1 to uint32_t before shifting to avoid overflow on 16-bit machines. Limit bitPos to 0-31 for uint32_t. For checking validity: if (bitPos >= 0 && bitPos < 32). Use bit() macro as an alternative: digitalWrite(pin, bit(bitPos)).
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
← Previous
Arduino analogRead Returns 1023 Always
Next →
Arduino Byte Order (Endianness) Causes Data Corruption
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro