Skip to content

Read and Write Big-Endian Fields

The Course
•
40 min study

The telemetry frame stores its payload length, sensor ID and value as two-octet numbers. Two octets can be combined in two orders. Big-endian, also called network byte order, puts the most significant octet first: the number 258 is 01 02. Little-endian puts the least significant octet first: 258 is 02 01. Most desktop CPUs are little-endian in memory, while most network protocols, including this one, are big-endian on the wire. A decoder that gets this wrong reads sensor 1 as sensor 256 and passes every test you wrote on the same wrong assumption.

The fix is to never ask the CPU how it stores numbers. Read individual octets and build the value with arithmetic. Shifts and ORs operate on values, not on memory layout, so (high << 8) | low produces the same number on every machine.

Predict and run

Read the program before pressing Run. Write down its output and say which part of the expression decides the byte order.

Predict before running C
#include <stdio.h>

unsigned long read_u16(const unsigned char *bytes) {
    return ((unsigned long)bytes[0] << 8) | bytes[1];
}

int main(void) {
    unsigned char bytes[2] = {0x01,0x02};
    printf("%lu\n", read_u16(bytes));
    return 0;
}
Check your prediction
Text
258

bytes[0] is shifted left by 8, so it becomes the high octet: 1 times 256 is 256. OR-ing in bytes[1] adds 2, because the low eight bits of the shifted value are all zero. The byte order lives entirely in which index gets shifted. Swap the indexes and the same function reads little-endian.

Same bytes, two conventions

The next program decodes the same two octets both ways, which is exactly the disagreement a sender and receiver have when one of them uses the wrong convention:

Big-endian versus little-endian C
#include <stdio.h>

unsigned long read_be16(const unsigned char *b) { return ((unsigned long)b[0] << 8) | b[1]; }
unsigned long read_le16(const unsigned char *b) { return ((unsigned long)b[1] << 8) | b[0]; }

int main(void) {
    const unsigned char samples[3][2] = {{0x01, 0x02}, {0x00, 0x04}, {0x27, 0x10}};
    for (size_t i = 0; i < 3; ++i) {
        printf("%02X %02X: big %lu, little %lu\n", (unsigned)samples[i][0], (unsigned)samples[i][1],
               read_be16(samples[i]), read_le16(samples[i]));
    }
    return 0;
}
Text
01 02: big 258, little 513
00 04: big 4, little 1024
27 10: big 10000, little 4135

The middle row is the frame's length field. Read little-endian, a valid four-byte payload looks like 1024 bytes, which the decoder would reject as oversized. The last row is the largest legal reading value, 10000. Neither function looked at how this CPU lays out integers.

Why the cast comes before the shift

The cast to unsigned long is not decoration. In C, an unsigned char operand is first promoted to int. Without the cast, bytes[0] << 8 is an int shift. The standard only guarantees that int holds values up to 32767, so on a 16-bit int implementation 255 << 8 is 65280, which does not fit. Shifting a signed value into a result it cannot represent is undefined behavior.

On today's 32-bit int, the two-octet case happens to fit, but the same habit breaks one size up:

C
unsigned long read_u32_wrong(const unsigned char *b) {
    return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];   /* b[0] << 24 is an int shift */
}

When b[0] is 0x80 or more, b[0] << 24 overflows a 32-bit int. UndefinedBehaviorSanitizer reports it at run time:

Shell
runtime error: left shift of 255 by 24 places cannot be represented in type 'int'

Without a sanitizer, the result often looks right, and then the optimizer, which may assume undefined behavior never happens, transforms surrounding code in ways that do not match your intent. Casting each octet to a wide unsigned type first makes every shift well defined. unsigned long is guaranteed at least 32 bits, so it can hold any 32-bit field.

A correct 32-bit read C
#include <stdio.h>

unsigned long read_be32(const unsigned char *b) {
    return ((unsigned long)b[0] << 24) | ((unsigned long)b[1] << 16) |
           ((unsigned long)b[2] << 8) | (unsigned long)b[3];
}

int main(void) {
    const unsigned char bytes[4] = {0xFF, 0x00, 0x00, 0x01};
    printf("%lu\n", read_be32(bytes));
    return 0;
}
Text
4278190081

Writing reverses the steps

Encoding takes a value apart. The high octet is value >> 8; the low octet is value & 0xFF. Before narrowing to unsigned char, check the value fits the field: converting 70000 to two octets silently drops the top bits and sends 4464 instead. The project's record fields use uint_least16_t, a type guaranteed to exist on every C implementation, rather than uint16_t, which is optional. Explicit byte operations mean the field's in-memory width never leaks onto the wire.

Practice

Exercise

Your turn

Some formats use a 3-byte big-endian field, for example a 24-bit sequence number. Nothing above handles that width, so apply the idea rather than the code. Write unsigned long read_be24(const unsigned char *b) and int write_be24(unsigned char out[3], unsigned long value). write_be24 returns 0 and leaves out unchanged when value does not fit in 24 bits. Decode {0,0,0}, {0,1,2} and {0xFF,0,1}, then encode 1193046 and try to encode 16777216 into the same array. Print:

Text
00 00 00 -> 0
00 01 02 -> 258
FF 00 01 -> 16711681
encode 1193046: 12 34 56
encode 16777216: rejected, bytes 12 34 56
Your workspace C
#include <stdio.h>

int main(void) {
    const unsigned char samples[3][3] = {{0, 0, 0}, {0, 1, 2}, {0xFF, 0, 1}};
    unsigned char out[3] = {0, 0, 0};
    /* Write read_be24 and write_be24 above, then use them here. */
    (void)samples; (void)out;
    return 0;
}
Hint 1: the idea

The first octet on the wire holds the top 8 of the 24 bits, so it moves by 16, not 24. Reading needs every octet widened before its shift. Writing needs a range check before any byte of out is touched, so a rejected value leaves the previous encoding intact.

Hint 2: a first step

Write read_be24 alone and run the three decode lines. If the last one prints anything larger than 16777215 (the biggest 24-bit value), your shifts are still those of a 32-bit field. For write_be24, first work out on paper which three octets 1193046 (hexadecimal 0x123456) should produce, then write the stores and only after that the range check.

Show one solution
Run the solution C
#include <stdio.h>

unsigned long read_be24(const unsigned char *b) {
    return ((unsigned long)b[0] << 16) | ((unsigned long)b[1] << 8) | (unsigned long)b[2];
}

int write_be24(unsigned char out[3], unsigned long value) {
    if (value > 0xFFFFFFUL) { return 0; }
    out[0] = (unsigned char)(value >> 16);
    out[1] = (unsigned char)((value >> 8) & 0xFFUL);
    out[2] = (unsigned char)(value & 0xFFUL);
    return 1;
}

int main(void) {
    const unsigned char samples[3][3] = {{0, 0, 0}, {0, 1, 2}, {0xFF, 0, 1}};
    unsigned char out[3] = {0, 0, 0};
    for (size_t i = 0; i < 3; ++i) {
        const unsigned char *s = samples[i];
        printf("%02X %02X %02X -> %lu\n", (unsigned)s[0], (unsigned)s[1], (unsigned)s[2], read_be24(s));
    }
    if (write_be24(out, 1193046UL)) {
        printf("encode 1193046: %02X %02X %02X\n", (unsigned)out[0], (unsigned)out[1], (unsigned)out[2]);
    }
    if (!write_be24(out, 16777216UL)) {
        printf("encode 16777216: rejected, bytes %02X %02X %02X\n", (unsigned)out[0], (unsigned)out[1],
               (unsigned)out[2]);
    }
    return 0;
}
Text
00 00 00 -> 0
00 01 02 -> 258
FF 00 01 -> 16711681
encode 1193046: 12 34 56
encode 16777216: rejected, bytes 12 34 56

The largest 24-bit value is 0xFFFFFF, 16777215, so 16777216 is the first value that cannot be encoded; the check compares against that constant before any store. The middle octet needs both a shift and a mask, because value >> 8 still holds the top byte above it. The FF sample decodes to 16711681 because the top octet is widened before its 16-bit shift. Next, masks and shifts get a closer look, along with the bounds arithmetic that keeps every read inside the buffer.

Was this article helpful?

Your response is saved on this device.