Skip to content

Ard Byte High

DodaTech 1 min read

In this tutorial, you'll learn about Arduino High Byte Extraction Returns Wrong Value. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Extracting the high byte from a 16-bit value gives incorrect results.

Quick Fix

Wrong

int val = 0xABCD;
byte h = val >> 8;  // Works, but only for 16-bit
h = 0xAB (correct), but may fail for signed negative values.
uint16_t val = 0xABCD;
byte highByte = highByte(val);  // Returns 0xAB
byte lowByte = lowByte(val);    // Returns 0xCD

Serial.print("High: 0x");
Serial.println(highByte, HEX);
Serial.print("Low: 0x");
Serial.println(lowByte, HEX);
High: 0xAB
Low: 0xCD

Prevention

Use the built-in highByte() and lowByte() macros for safe byte extraction. These work with uint16_t. For signed int values, cast to uint16_t first to avoid sign extension issues. For 32-bit values, use manual shifting: byte b3 = (val >> 24) & 0xFF.

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

FAQ

### Do highByte/lowByte work with int?

Yes, but for negative signed int values, the high byte includes sign extension. Cast to uint16_t for correct results.

What is the difference between highByte() and manual shifting?

highByte() is equivalent to ((val) >> 8) and lowByte() is equivalent to ((val) & 0xFF). They are just convenience macros.

How do I extract bytes from a 32-bit value?

Byte 0: val & 0xFF, Byte 1: (val >> 8) & 0xFF, Byte 2: (val >> 16) & 0xFF, Byte 3: (val >> 24) & 0xFF.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro