What are Union Byte Access in C- Best C Language Course For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Union Byte Access in C

Lecture 48 of our free C programming course: detect byte order and dump the raw bytes of any structure using a union.

Chapter 10

Structure and Union

Level

Intermediate

Reading time

12 minutes

Union byte access is the trick of overlaying a multi-byte value with an array of bytes so you can look at, or change, individual bytes without pointer casts. It is one of the most useful low-level skills in embedded C programming, and it is a favourite question in firmware interviews. In this lecture of our free C tutorial you will write a byte order detector, then go further and view the raw bytes of an entire structure, including the hidden padding the compiler inserts. Every example is original, compiled with gcc, and shows real output.

What You Will Learn

  • How to overlay an integer with a byte array using a union
  • How to detect little-endian or big-endian at run time
  • How to make the byte array size match the type automatically
  • How to dump the raw bytes of a structure and spot padding
  • What the C standard says about reading a different union member

Prerequisites

Complete the previous lecture on little vs big endian and know how union members share storage. A gcc installation on Linux, or an online C compiler, is all you need for this free embedded C course exercise.

Union Byte Access: Overlaying an Integer

A union places all members at the same address. If one member is a 32-bit integer and another is an array of four bytes, then writing the integer lets you read its bytes in memory order through the array. Element zero of the byte array is the byte at the lowest address.

union probe : two names for the same four bytes
pr.word0x01020304 (one 32-bit value)
pr.byte[]byte[0]byte[1]byte[2]byte[3]
little-endian04030201
big-endian01020304

If byte[0] holds the least significant byte (0x04), the machine is little-endian. If it holds 0x01, the machine is big-endian.

Making the Array Size Portable

Instead of hard-coding the number of bytes, let the compiler compute it with sizeof. That way the same union works if you later change the integer type, and it stays correct on targets where an integer has a different width.

Complete Program: Byte Order and Structure Dump

/* file: union_bytes.c */
#include <stdio.h>
#include <stdint.h>
#include <string.h>

union probe {
    uint32_t word;
    uint8_t  byte[sizeof(uint32_t)];
};

struct sensor_msg {
    uint8_t  id;
    uint16_t value;
    uint8_t  flags;
};

union msg_view {
    struct sensor_msg msg;
    uint8_t raw[sizeof(struct sensor_msg)];
};

int main(void)
{
    union probe pr;
    union msg_view mv;

    pr.word = 0x01020304u;
    printf("%s endian\n", pr.byte[0] == 0x04 ? "Little" : "Big");

    memset(&mv, 0, sizeof mv);
    mv.msg.id = 0x07;
    mv.msg.value = 0x1234;
    mv.msg.flags = 0x80;

    printf("sizeof(struct sensor_msg) = %zu\n", sizeof(struct sensor_msg));
    for (size_t i = 0; i < sizeof mv.raw; i++)
        printf("%02X ", mv.raw[i]);
    putchar('\n');
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o union_bytes union_bytes.c
$ ./union_bytes
Little endian
sizeof(struct sensor_msg) = 6
07 00 34 12 80 00

Union Byte Access: Reading the Structure Dump

The structure holds only four bytes of real data (1 + 2 + 1), yet sizeof reports six. The dump shows why. The compiler inserted padding so that the 16-bit field starts at an even offset.

Raw bytes of struct sensor_msg on a little-endian target
offset012345
content07 id00 pad34 value low12 value high80 flags00 pad
OffsetByteMeaning
007id
100padding inserted for alignment
2 to 334 12value 0x1234, low byte first because the machine is little-endian
480flags
500tail padding so arrays of this structure stay aligned

Padding bytes are not yours. The zeros at offsets 1 and 5 are there only because the program called memset first. Without it, padding may hold leftover garbage, and the standard says nothing about its value. Never rely on padding contents.

What the C Standard Says

Since C99 (clarified by technical corrigendum and kept in C11), reading a union member other than the one last written is allowed: the bytes are reinterpreted in the new type. Two caveats matter for embedded work:

  • The result depends on the implementation. Byte order, padding and representation are all up to the compiler and CPU.
  • Reading bytes that do not form a valid value for the new type (for example a trap representation) is undefined behaviour.

C++ is stricter and does not guarantee this behaviour, so if you share a header between C and C++ code, use memcpy for the reinterpretation instead.

TechniqueProsCons
Union overlayReadable, no casts, works in C99 and laterNot guaranteed in C++
unsigned char pointerAlways legal for inspecting any objectSlightly more verbose
memcpy into a second objectLegal in both C and C++Extra copy, though compilers optimise it away
Shifts and masksFully portable across byte ordersMore code to write

Real-World Union Byte Access Uses

  • Debugging: dump a structure to the UART to see exactly what a peer will receive.
  • Checksums: run a CRC over the raw bytes of a header without pointer casts.
  • Register access: split a 32-bit register read into bytes for a byte-wide bus.
  • Porting: detect byte order once at start-up and choose swap routines.

Common Union Byte Access Mistakes

  • Hard-coding char c[2] for a type that is four bytes wide, so only half the bytes are examined.
  • Using plain char for the byte array and getting sign-extension surprises when printing. Prefer uint8_t or unsigned char.
  • Sending a structure dump to another machine and assuming it has the same padding and byte order.
  • Forgetting to clear the union before dumping, which leaks old stack data in the padding.

Union Byte Access Best Practices

Safe byte-level work

  • Size byte arrays with sizeof of the type they overlay.
  • Use uint8_t or unsigned char for raw bytes.
  • Serialise protocol messages field by field with shifts, not by dumping the in-memory structure.
  • If packing is truly required, use your compiler’s packed attribute deliberately and measure the alignment cost on your core.

Performance and Security Considerations

A union overlay costs nothing at run time: both names refer to the same memory, so there is no copy and no extra instruction. A memcpy into another object looks heavier, but optimising compilers recognise small fixed-size copies and generate the same code as a union read. Choose by clarity and portability, not by fear of overhead.

On the security side, dumping a structure with uninitialised padding sends stale stack or heap bytes to whoever reads the output. That is a real information leak in firmware that logs or transmits raw structures. Clear the object with memset before filling it, or better, serialise field by field so padding never leaves the device.

Practice Exercise

Add a fourth field, uint32_t timestamp, to struct sensor_msg. Predict the new sizeof, the position of every padding byte, and the byte dump before running the program. Then reorder the fields from largest to smallest and compare the sizes. You will see how field order alone can shrink a structure.

Summary and Key Takeaways

  • Union byte access, an integer overlaid with a byte array, shows individual bytes in memory order.
  • Byte 0 equal to the low byte means little-endian; equal to the high byte means big-endian.
  • Structures contain padding, so sizeof can exceed the sum of the fields.
  • Union reinterpretation works in C but is implementation-dependent; use shifts for wire formats.

Frequently Asked Questions

How does union byte access detect endianness?

Overlay a 32-bit integer holding 0x01020304 with a byte array and test whether the first byte equals 0x04. If so the machine is little-endian.

Is union type punning legal in C?

Yes in C99 and later, but the resulting value is implementation-defined. It is not guaranteed in C++.

Why is sizeof larger than the total of my fields?

The compiler adds padding to keep each field aligned for fast access.

Can I write a structure straight to a file or socket?

You can, but the file will contain padding and your CPU’s byte order, so another system may misread it. Serialise field by field instead.

Why use uint8_t instead of char?

Plain char may be signed, which can print negative numbers for bytes above 0x7F. uint8_t is always unsigned.

Which is better, a union or a pointer cast?

For inspection, an unsigned char pointer is always legal. For readable overlays in C code, a union is clear and widely used in firmware.

Free Embedded C Programming Course

Master pointers, structures, unions and typedef with original examples, output and quizzes.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →