Skip to content

Ard Bit Read

DodaTech 1 min read

In this tutorial, you'll learn about Arduino Reading a Bit Returns Wrong Boolean. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Checking if a bit is set returns true when the bit is not actually set.

Quick Fix

Wrong

uint8_t flags = 0b00001000;
if (flags & (1 << 3)) {  // Correct check
  // Bit 3 is set
}
This works correctly, but using == 1 fails.
uint8_t flags = 0b00001000;

// Check if bit 3 is set
if (flags & (1 << 3)) {
  Serial.println("Bit 3 is SET");
} else {
  Serial.println("Bit 3 is CLEAR");
}

// Check if bit 3 is clear
if (!(flags & (1 << 3))) {
  Serial.println("Bit 3 is CLEAR");
}

// Get bit value as 0 or 1
bool bit3 = (flags >> 3) & 1;
Serial.print("Bit 3 value: ");
Serial.println(bit3);
Bit 3 is SET
Bit 3 value: 1

Prevention

Use (flags & (1 << n)) as a boolean — it evaluates to non-zero (true) if the bit is set. Do NOT compare: (flags & (1 << n)) == 1. This fails because (1 << n) & flags equals 2^n, not 1. Use (flags >> n) & 1 to get a clean 0 or 1.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Why does (flags & (1<<3)) == 1 fail?

If bit 3 is set, flags & (1<<3) = 0x08 = 8, not 1. So 8 == 1 is false. The == only works for bit 0.

How do I test multiple bits at once?

if ((flags & 0b00011000) == 0b00011000) checks if both bits 3 and 4 are set.

Can I read bits from a hardware register?

Yes. The same bitwise operations work on hardware registers like PIND, PINB. These are volatile and may change between reads.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro