Skip to content

Ard Byte Low

DodaTech 1 min read

In this tutorial, you'll learn about Arduino Low Byte Masking Fails for Signed Values. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Masking the low byte of a signed integer produces unexpected negative values.

Quick Fix

Wrong

int val = -1;
byte low = val & 0xFF;  // Works, but val & 0xFF is int on AVR
low = 255 (0xFF) — looks correct but type issues arise.
int16_t sensorVal = analogRead(A0) - 512;
uint16_t unsignedVal = (uint16_t)sensorVal;
byte low = unsignedVal & 0xFF;
byte high = (unsignedVal >> 8) & 0xFF;

Serial.print("Low: ");
Serial.print(low);
Serial.print(" High: ");
Serial.println(high);
Low: 0 High: 1  (varies with sensorVal).

Prevention

Always use unsigned types (uint16_t, uint32_t) when doing byte extraction. Signed right-shift performs sign extension, filling high bits with 1s for negative values. The & 0xFF mask correctly extracts the low byte regardless of sign, but the intermediate type matters.

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

FAQ

### What is sign extension?

When right-shifting a signed negative number, the most significant bit (sign) is replicated. -1 (0xFFFF) >> 8 = 0xFFFF, not 0x00FF.

Does Arduino int have 2 or 4 bytes?

On AVR (Uno, Mega), int is 2 bytes (16-bit). On ESP32, Due, Zero, int is 4 bytes (32-bit). Use uint16_t explicit sizing for portable code.

Why use uint16_t instead of int?

uint16_t is always 16-bit unsigned on all platforms. int varies — use fixed-width types for byte manipulation.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro