Reading history

Endianness and Byte Order in C

6 min read 1 views

Learn little-endian and big-endian byte order in C, test your machine, and read and write numbers portably with shifts and masks.

A 32-bit number takes 4 bytes in memory. But in which order are those 4 bytes stored? Most computers today put the smallest byte first, while network protocols send the biggest byte first. This choice is called endianness. You can ignore it for everyday arithmetic, but it matters the moment you save numbers to a file, send them over a network, or read a file format made on another machine.

In this lesson you will learn

  • What little-endian and big-endian mean
  • How to see the bytes of a number, and test your machine’s order
  • Why shifts and masks do not depend on byte order
  • Writing and reading numbers in a fixed byte order
  • Swapping bytes

You should know bitwise operators, fixed-width integers and memcpy.

uint32_t value = 0x12345678Little-endian (Intel, AMD, most Arm)78addr +056addr +134addr +212addr +3memory →Big-endian (network byte order)12addr +034addr +156addr +278addr +3memory →Same value, same bytes, different order in memory

Seeing the Bytes

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int main(void) {
    /* Look at the bytes of a 32-bit number in memory */
    uint32_t value = 0x12345678;
    unsigned char bytes[4];
    memcpy(bytes, &value, sizeof value);
    printf("0x%08X in memory: %02X %02X %02X %02X\n",
           (unsigned)value, bytes[0], bytes[1], bytes[2], bytes[3]);

    /* Test the machine's byte order */
    uint16_t probe = 1;
    unsigned char first;
    memcpy(&first, &probe, 1);
    printf("this machine is %s-endian\n", first == 1 ? "little" : "big");

    /* Byte order does not affect values or arithmetic, only memory layout */
    printf("value + 1 = 0x%08X on every machine\n", (unsigned)(value + 1));

    /* Getting bytes with shifts gives the same answer on every machine */
    printf("most significant byte with shifts: %02X\n", (unsigned)((value >> 24) & 0xFF));
    printf("least significant byte with shifts: %02X\n", (unsigned)(value & 0xFF));
    return 0;
}

Output

0x12345678 in memory: 78 56 34 12
this machine is little-endian
value + 1 = 0x12345679 on every machine
most significant byte with shifts: 12
least significant byte with shifts: 78
  • 0x12345678 has four bytes: 12 is the most significant (biggest place value) and 78 the least significant.
  • Copying the number into a byte array shows the real memory order: 78 56 34 12. The smallest byte comes first, so this machine is little-endian. Intel and AMD processors, and Arm in its usual mode, all work this way.
  • A big-endian machine would show 12 34 56 78. Network protocols such as TCP/IP use this order, which is why it is also called network byte order.
  • The probe stores 1 in a 2-byte number and looks at the first byte. If it is 1, the small end comes first.
  • Byte order only affects how a number sits in memory. Arithmetic, comparisons and the shifts value >> 24 and value & 0xFF work on the value, so they give the same answer everywhere.

Writing Portable Data

#include <stdio.h>
#include <stdint.h>

/* Write a 32-bit number as 4 bytes in big-endian ("network") order */
static void put_be32(unsigned char *out, uint32_t v) {
    out[0] = (unsigned char)(v >> 24);
    out[1] = (unsigned char)(v >> 16);
    out[2] = (unsigned char)(v >> 8);
    out[3] = (unsigned char)v;
}

/* Read it back: works the same on little- and big-endian machines */
static uint32_t get_be32(const unsigned char *in) {
    return (uint32_t)in[0] << 24 | (uint32_t)in[1] << 16 |
           (uint32_t)in[2] << 8  | (uint32_t)in[3];
}

/* Little-endian versions, used by many file formats such as BMP and ZIP */
static void put_le16(unsigned char *out, uint16_t v) {
    out[0] = (unsigned char)v;
    out[1] = (unsigned char)(v >> 8);
}
static uint16_t get_le16(const unsigned char *in) {
    return (uint16_t)(in[0] | in[1] << 8);
}

/* Reverse the byte order of a 32-bit value */
static uint32_t swap32(uint32_t v) {
    return (v >> 24) | ((v >> 8) & 0x0000FF00u) | ((v << 8) & 0x00FF0000u) | (v << 24);
}

int main(void) {
    unsigned char buf[6];
    uint32_t amount = 1500000;       /* 0x0016E360 */
    uint16_t port = 8080;            /* 0x1F90 */

    put_be32(buf, amount);
    put_le16(buf + 4, port);
    printf("buffer bytes: ");
    for (int i = 0; i < 6; i++) printf("%02X ", buf[i]);
    printf("\n");

    printf("read back: amount=%u port=%u\n", (unsigned)get_be32(buf), (unsigned)get_le16(buf + 4));
    printf("swap32(0x12345678) = 0x%08X\n", (unsigned)swap32(0x12345678u));
    printf("swap32 twice gives back 0x%08X\n", (unsigned)swap32(swap32(0x12345678u)));
    return 0;
}

Output

buffer bytes: 00 16 E3 60 90 1F 
read back: amount=1500000 port=8080
swap32(0x12345678) = 0x78563412
swap32 twice gives back 0x12345678
  • put_be32 takes the number apart with shifts and stores the biggest byte first. Because shifts work on values, this code produces the same bytes on any computer.
  • get_be32 rebuilds the number by shifting each byte back into place. Casting each byte to uint32_t before shifting avoids overflow in the << 24.
  • Many file formats, such as BMP images and ZIP archives, use little-endian, so the program shows put_le16 and get_le16 too. 8080 is 0x1F90, stored as 90 1F.
  • Following the format’s rule, instead of copying raw memory, is what makes a file readable on every machine.
  • swap32 reverses the four bytes. Swapping twice gives back the original value.

Library helpers

For network programs, POSIX systems offer htonl, htons, ntohl and ntohs in <arpa/inet.h> (“host to network long” and so on). They are used in socket programming. The shift-based functions in this lesson do the same job in plain standard C.

Common Mistakes

  1. Writing raw structs or ints to a file and expecting another machine to read them correctly.
  2. Reading bytes through a cast pointer, such as *(uint32_t *)buf. Besides byte order, this can break alignment rules. Use shifts or memcpy.
  3. Shifting a char without casting it first. A signed char with a high bit can turn into a negative number; use unsigned char buffers.
  4. Swapping bytes “just in case”. Swap only when the format’s order differs from the data you have, or better, always use put and get functions.

Practice Exercises

Exercise 1. How is the 16-bit value 0xABCD stored on a little-endian machine, and how in network byte order?

Show answer

Little-endian: CD AB. Network (big-endian) order: AB CD.

Exercise 2. Write uint32_t get_le32(const unsigned char *in), which reads a little-endian 32-bit number.

Show answer
uint32_t get_le32(const unsigned char *in) {
    return (uint32_t)in[0]       | (uint32_t)in[1] << 8 |
           (uint32_t)in[2] << 16 | (uint32_t)in[3] << 24;
}

The first byte is the smallest, so it is not shifted at all.

Frequently Asked Questions

Where do the names little-endian and big-endian come from?

From Jonathan Swift’s novel Gulliver’s Travels, where two nations fight over which end of a boiled egg to crack first. The computer scientist Danny Cohen borrowed the joke in 1980 to describe the byte-order debate.

Does endianness affect strings?

No. A string is an array of single bytes, stored in order, so “ABC” looks the same on every machine. Only values that take more than one byte, such as int, float or UTF-16 text, are affected.

Summary

  • Little-endian stores the smallest byte first; big-endian (network order) the biggest.
  • Most computers are little-endian; many network and file formats fix their own order.
  • Shifts and masks work on values, so they are the same on every machine.
  • Use put and get functions with shifts to read and write data in a fixed order.

Next: The volatile and restrict Keywords in C.

Lessons are also marked complete when you click Next.

Leave a Reply

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