Skip to content

Ard Byte Bitshift

DodaTech 1 min read

In this tutorial, you'll learn about Arduino Bitshift Operation Gives Wrong Result. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Shifting bits left or right produces unexpected values.

Quick Fix

Wrong

int val = 1 << 16;  // 16-bit int overflow!
val = 0 (overflow on 16-bit int, 1 shifted beyond 15 bits).
uint8_t a = 0b00110011;
uint8_t b = 0b11001100;
uint8_t result = (a << 4) | (b >> 4);

Serial.print("Combined: 0b");
Serial.println(result, BIN);

// Safe 32-bit shift
uint32_t bigVal = (uint32_t)1 << 20;
Serial.print("2^20: ");
Serial.println(bigVal);
Combined: 0b00111100
2^20: 1048576

Prevention

On AVR (16-bit int), shifting a 1 beyond 15 bits overflows the int. Cast to uint32_t or use 1UL before shifting beyond 15. Shift amount must be less than the type width (e.g., << 16 on uint16_t is undefined behavior). For rotating bits, combine left and right shifts with OR.

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

FAQ

### What is undefined behavior in bit shifting?

Shifting by >= the bit width of the type (e.g., << 16 on 16-bit int) or shifting a negative value is undefined behavior — the compiler may produce unexpected results.

How do I rotate bits?

Use (val << n) | (val >> (width - n)) for left rotation. Width is 8, 16, or 32 depending on the type.

What does the BIN format do?

Serial.println(val, BIN) prints the value in binary format (e.g., 00110011). Other formats: DEC (decimal), HEX (hexadecimal), OCT (octal).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro