Skip to content

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.
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

### What is the bit() macro?

bit(n) is defined as (1 << (n)). It is a convenience macro in Arduino.h for creating bit masks.

Can I use bit() with variable?

Yes: flags |= bit(bitPos). It expands to (1 << (bitPos)).

What is the max bit position for uint32_t?

0-31 (32 bits total). Shifting by 32 or more is undefined behavior.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro