Skip to content

Bytes Are Not Text or Structs

The Course
•
40 min study

A sensor sends ten bytes. Your program has a struct with a sensor ID and a value. The tempting shortcut is to treat the bytes as the struct: cast the buffer to Reading * and read the fields, or fwrite a struct and call it the file format. That shortcut works on the machine where you wrote it and fails somewhere else, sometimes silently. The bytes on the wire are defined by the protocol, while the bytes of a struct in memory are defined by your compiler and CPU. They are different things, and the decoder's job is to translate between them one byte at a time.

This lesson fixes the vocabulary for the rest of the course. An octet is exactly eight bits, the unit the protocol is written in. In C, the byte type is unsigned char, and its width is CHAR_BIT bits. The standard only promises CHAR_BIT >= 8. Every mainstream platform uses 8, but some digital signal processors use 16 or 32. Rather than silently assuming, the project's header states the requirement where the compiler can check it:

C
_Static_assert(CHAR_BIT == 8, "Telemetry format requires 8-bit bytes");

Predict and run

Read the program before pressing Run. Write down its output and say which statement produces each line.

Predict before running C
#include <stdio.h>

int main(void) {
    unsigned char bytes[3] = {0x54,0x00,0xff};
    for (size_t i = 0; i < 3; ++i) { printf("%02X\n", (unsigned)bytes[i]); }
    return 0;
}
Check your prediction
Text
54
00
FF

%02X prints an unsigned int as at least two uppercase hex digits, padding with zero. The cast to unsigned matters: an unsigned char argument is promoted to int when passed to printf, and %X expects unsigned int. The cast makes the argument type match the format exactly. The middle line is a zero byte, which is ordinary data here. A string function would treat it as the end of the text.

Why the byte type is unsigned char

Plain char may be signed or unsigned; the choice belongs to the implementation. On x86 it is usually signed, on many ARM systems unsigned. If you store the octet 0xFF in a signed type, it holds -1, and integer promotion keeps that negative value:

The same eight bits, two meanings C
#include <stdio.h>

static int is_ff(int byte) { return byte == 0xFF; }

int main(void) {
    signed char as_signed = -1;
    unsigned char as_octet = (unsigned char)as_signed;
    printf("signed value: %d\n", as_signed);
    printf("octet value: %u\n", (unsigned)as_octet);
    printf("equals 0xFF: %s\n", is_ff(as_signed) ? "yes" : "no");
    printf("octet equals 0xFF: %s\n", is_ff(as_octet) ? "yes" : "no");
    return 0;
}
Text
signed value: -1
octet value: 255
equals 0xFF: no
octet equals 0xFF: yes

Passing as_signed to is_ff promotes -1 to int, and -1 is not 255, so the test is false. Written inline as as_signed == 0xFF, Clang even refuses it under -Werror, warning that the comparison "is always false"; hidden behind a helper, as in real code, nothing warns you. A magic-byte check written that way would reject a valid frame on one platform and accept it on another. Converting to unsigned char is well defined: it reduces the value modulo 256, so -1 becomes 255. Keep wire data in unsigned char from the moment it enters your program and this whole class of bug disappears.

Why a struct is not a wire format

Consider a header struct that seems to match five wire bytes:

C
typedef struct {
    unsigned char magic;
    unsigned char version;
    unsigned char type;
    uint16_t length;
} Header;

const Header *header = (const Header *)buffer;   /* do not do this */

That cast fails in four independent ways:

  • Padding. The compiler may insert padding before length so it starts at an even address. On typical platforms sizeof(Header) is 6, not 5, and length sits at offset 4 instead of 3.
  • Byte order. A uint16_t in memory uses the CPU's byte order. The protocol says big-endian. On a little-endian machine, length 00 04 would read as 1024.
  • Alignment. If buffer + offset is not suitably aligned for uint16_t, reading through the cast pointer is undefined behavior. Some CPUs trap; others just run slower.
  • Effective type. C's aliasing rules say an object whose type is "array of unsigned char" may not be read through an lvalue of a different struct type. Optimizers rely on that rule to reorder loads and stores, so the code can break only at higher optimization levels.

Any one of these is a bug. Together they make the struct shortcut unfixable in portable C. The rule for this course is simple: never cast incoming bytes to a struct pointer, and never write sizeof(struct) raw bytes as output.

Decode each field from bytes

The portable version reads each field by its documented offset and combines bytes with arithmetic. It works for any padding, any CPU byte order and any buffer alignment, because it only ever reads unsigned char values:

Decode a header field by field C
#include <stdio.h>

typedef struct { unsigned magic, version, type; unsigned long length; } Header;

int main(void) {
    const unsigned char wire[5] = {0x54, 0x01, 0x01, 0x00, 0x04};
    Header header;
    header.magic = wire[0];
    header.version = wire[1];
    header.type = wire[2];
    header.length = ((unsigned long)wire[3] << 8) | wire[4];
    printf("magic %02X, version %u, type %u, length %lu\n",
           header.magic, header.version, header.type, header.length);
    return 0;
}
Text
magic 54, version 1, type 1, length 4

The struct is now just a convenient in-memory form. Its layout can be anything, because the translation code names every offset explicitly. The next lesson explains the shift-and-OR expression in detail.

Practice

Exercise

Your turn

Write void dump(const unsigned char *bytes, size_t size) that prints each byte as offset: XX in two-digit uppercase hex, then prints how many bytes were zero. Call it on {0x54, 0x00, 0xFF, 0x80}. Print:

Text
0: 54
1: 00
2: FF
3: 80
Zero bytes: 1
Your workspace C
#include <stdio.h>

int main(void) {
    const unsigned char bytes[4] = {0x54, 0x00, 0xFF, 0x80};
    /* Write dump above and call it here. */
    (void)bytes;
    return 0;
}
Hint 1: the idea

The size comes from the caller, not from a terminator, so a zero byte is counted like any other. Bytes 0xFF and 0x80 would be negative in a signed char; in unsigned char they are 255 and 128.

Hint 2: a first step

Write the loop that prints each index and byte first, and check it against the expected lines; a byte above 0x7F tells you whether your cast is right. Add the zero count only once every byte prints correctly.

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

void dump(const unsigned char *bytes, size_t size) {
    size_t zeros = 0;
    for (size_t i = 0; i < size; ++i) {
        printf("%zu: %02X\n", i, (unsigned)bytes[i]);
        if (bytes[i] == 0) { ++zeros; }
    }
    printf("Zero bytes: %zu\n", zeros);
}

int main(void) {
    const unsigned char bytes[4] = {0x54, 0x00, 0xFF, 0x80};
    dump(bytes, sizeof bytes);
    return 0;
}
Text
0: 54
1: 00
2: FF
3: 80
Zero bytes: 1

Each format specifier matches its argument: %zu for size_t, %02X for the unsigned cast. A mismatch such as passing size_t to %d is undefined behavior, and -Wall warns about it. A dump like this is the first tool you reach for when a decoder disagrees with a fixture. Next, you combine two octets into a 16-bit big-endian value without relying on the CPU's byte order.

Was this article helpful?

Your response is saved on this device.