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).
Right
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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro