Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Counting and finding bits
    4. Comparing bit fingerprints with popcount
    5. Rotating: std::rotl and std::rotr
    6. std::bitset: a fixed row of bits
    7. Seeing a float’s bits: std::bit_cast
    8. Why not cast the pointer?
    9. How a float is stored
    10. Endianness: the order of the bytes
    11. Reading a binary format
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Bit functions on a signed type
    16. Reading a number from a byte buffer through a cast pointer
    17. Try it yourself

    Module 9 · Performance

    9.5Bits, bit_cast and endianness

    Count and find bits with one call, see the exact bits of a float with std::bit_cast, and read numbers from binary files whatever order their bytes are in.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Counting and finding bits
    4. Comparing bit fingerprints with popcount
    5. Rotating: std::rotl and std::rotr
    6. std::bitset: a fixed row of bits
    7. Seeing a float’s bits: std::bit_cast
    8. Why not cast the pointer?
    9. How a float is stored
    10. Endianness: the order of the bytes
    11. Reading a binary format
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Bit functions on a signed type
    16. Reading a number from a byte buffer through a cast pointer
    17. Try it yourself

    Key terms

    population count
    The number of 1 bits in an integer. std::popcount computes it.
    rotate
    A shift where the bits that fall off one end come back in at the other end.
    std::bit_cast<To>(from)
    Makes a To with exactly the bits of from. Both types must be the same size and trivially copyable (safe to copy byte by byte).
    strict aliasing rule
    Reading an object through a pointer to an unrelated type, like a float through a std::uint32_t*, is undefined behavior. Byte types (char, unsigned char, std::byte) are the exception.
    IEEE 754
    The standard format for floating-point numbers that float and double use on almost every machine: a sign bit, exponent bits and mantissa bits.
    mantissa
    The bits of a floating-point number that hold its digits. The exponent says where the binary point goes.
    endianness
    The order a number's bytes are stored in. Little-endian puts the lowest byte first; big-endian puts the highest byte first.
    std::byteswap
    Reverses the order of the bytes in an integer (C++23).

    Operators and bit operations showed how to set, clear and test bits with masks. Real code also asks questions about the bits themselves: how many are set, where the highest one is, what bits a float is made of, and in which order the bytes of a number sit in a file. The <bit> header answers each of these with one function call, and the compiler turns most of them into a single instruction.

    In 30 seconds

    • std::popcount, std::countl_zero, std::countr_zero, std::bit_width and std::has_single_bit count and find bits in an unsigned integer. std::rotl and std::rotr rotate them.
    • std::bit_cast<std::uint32_t>(f) gives you the bits of a float as an integer. Casting the pointer instead is undefined behavior.
    • A float is 1 sign bit, 8 exponent bits and 23 mantissa bits.
    • x86-64 stores the lowest byte of a number first. File formats fix their own byte order, so read their numbers byte by byte with shifts, or with std::byteswap.

    Counting and finding bits

    Each of these functions takes an unsigned integer and answers one question about its bits:

    FunctionAnswers
    std::popcount(x)How many bits are 1?
    std::countr_zero(x)How many 0 bits are below the lowest 1? (the position of the lowest 1)
    std::countl_zero(x)How many 0 bits are above the highest 1?
    std::bit_width(x)How many bits does x need? (the position of the highest 1, plus one)
    std::has_single_bit(x)Is exactly one bit set? (is x a power of two?)
    #include <bit>
    #include <cstdint>
    #include <print>
    
    std::uint32_t x = 0b0010'1100; // 44
    std::println("{:08b}", x);
    std::println("popcount     {}", std::popcount(x));
    std::println("countr_zero  {}", std::countr_zero(x));
    std::println("countl_zero  {}", std::countl_zero(x));
    std::println("bit_width    {}", std::bit_width(x));
    std::println("single bit   {}", std::has_single_bit(x));
    std::println("countl_zero of a byte: {}",
                 std::countl_zero(std::uint8_t{44}));
    std::println("bits for 20 values: {}", std::bit_width(19u));

    Output

    00101100
    popcount     3
    countr_zero  2
    countl_zero  26
    bit_width    6
    single bit   false
    countl_zero of a byte: 2
    bits for 20 values: 5

    std::countl_zero counts from the top of the type, so the same value 44 has 26 leading zeros as a 32-bit number and 2 as an 8-bit one. std::bit_width also answers a sizing question: the values 0 to n - 1 need std::bit_width(n - 1) bits. Four DNA bases need 2 bits, and twenty amino acids (0 to 19) need 5, as the last line shows.

    Comparing bit fingerprints with popcount

    A fast way to compare things is to reduce each one to a row of bits, a fingerprint, and count the bits where two fingerprints differ. a ^ b has a 1 wherever a and b differ, so std::popcount(a ^ b) is the number of differences, called the Hamming distance. Vector search tools do this with embeddings (an AI model’s vectors of floats) reduced to one sign bit per dimension, and chemistry tools compare molecule fingerprints with popcount too:

    #include <bit>
    #include <cstdint>
    #include <print>
    
    // 64-dimension embeddings, one sign bit per dimension
    std::uint64_t query = 0xF0F0'1234'ABCD'0001;
    std::uint64_t doc_a = 0xF0F0'1234'ABCD'0003;
    std::uint64_t doc_b = 0x0F0F'1234'ABCD'0001;
    std::println("distance to a: {}", std::popcount(query ^ doc_a));
    std::println("distance to b: {}", std::popcount(query ^ doc_b));

    Output

    distance to a: 1
    distance to b: 16

    Document a differs in one dimension and b in sixteen, so a is the closer match. Comparing two 64-dimension fingerprints costs one XOR and one count.

    Rotating: std::rotl and std::rotr

    A shift drops the bits that fall off the end. A rotation brings them back in at the other end, so no bit is lost. std::rotl(x, n) rotates left by n places, std::rotr(x, n) right. Hash functions use rotations to mix bits. Below, the top 1 that the shift drops comes back at the bottom after rotl:

    #include <bit>
    #include <cstdint>
    #include <print>
    
    std::uint8_t b = 0b1001'0110;
    std::println("{:08b} start", b);
    std::println("{:08b} shift left 1", static_cast<std::uint8_t>(b << 1));
    std::println("{:08b} rotl 1", std::rotl(b, 1));
    std::println("{:08b} rotr 2", std::rotr(b, 2));

    Output

    10010110 start
    00101100 shift left 1
    00101101 rotl 1
    10100101 rotr 2

    std::bitset: a fixed row of bits

    When you want a row of yes/no values with names for the operations instead of masks, std::bitset<N> from <bitset> holds N bits (N is fixed when you compile). It has set, reset, test, count (its popcount), all, any and []:

    #include <bitset>
    #include <print>
    
    std::bitset<12> seen; // one bit per sample, all 0
    seen.set(0);
    seen.set(3);
    seen[7] = true;
    std::println("{}", seen.to_string());
    std::println("{} set, sample 3: {}", seen.count(), seen.test(3));

    Output

    000010001001
    3 set, sample 3: true

    to_string prints bit 0 on the right, like {:b} does. Under the hood a std::bitset is an integer (or an array of them) with the masks written for you.

    Seeing a float’s bits: std::bit_cast

    A float and a std::uint32_t are both 4 bytes. std::bit_cast<std::uint32_t>(f) makes an integer with exactly the bits of f, so you can print them, test them or change them. It also works the other way:

    #include <bit>
    #include <cstdint>
    #include <print>
    
    float one = 1.0f;
    std::uint32_t bits = std::bit_cast<std::uint32_t>(one);
    std::println("{:#010x}", bits);
    std::println("{:032b}", bits);
    float next = std::bit_cast<float>(bits + 1);
    std::println("{}", next);

    Output

    0x3f800000
    00111111100000000000000000000000
    1.0000001

    {:#010x} prints in hexadecimal with a 0x prefix, padded to 10 characters. Adding 1 to the bits gives the very next float above 1.0: floats are spaced apart, and this shows by how much. std::bit_cast only compiles when both types are the same size and trivially copyable: safe to copy byte by byte, like numbers, plain structs of numbers and arrays of them (Layout, alignment and padding has more). std::bit_cast<std::uint32_t>(1.0) doesn’t compile, because a double is 8 bytes: use std::uint64_t for it.

    Why not cast the pointer?

    Older code reads the bits like this: *reinterpret_cast<std::uint32_t*>(&f). That reads a float object through a std::uint32_t*, which breaks the strict aliasing rule: it’s undefined behavior. The optimizer assumes a std::uint32_t* never points at a float, so it may reorder or drop reads and writes: a program that works at -O0 can read stale values at -O2. The sanitizers used here don’t check this rule, so the code seems to work while you test it. The old correct way is std::memcpy from <cstring>: copy the bytes into a std::uint32_t variable. Copying bytes is allowed between any trivially copyable types, and Reading a binary format uses it. std::bit_cast (C++20) does the same in one expression, checks the sizes for you, and also works in constexpr code.

    How a float is stored

    float follows IEEE 754 on this platform and nearly every other. Its 32 bits are three fields:

    Bits3130 to 2322 to 0
    Fieldsignexponentmantissa
    -6.25f11000000110010000000000000000000

    The value is ±1.mantissa × 2^(exponent − 127). The sign bit is 1 for negative numbers. The exponent is stored with 127 added, so that it never needs a sign. The mantissa holds the binary digits after the point; the 1. in front is implied and not stored. Shifts and masks pull the fields apart:

    #include <bit>
    #include <cstdint>
    #include <print>
    
    float value = -6.25f;
    std::uint32_t bits = std::bit_cast<std::uint32_t>(value);
    std::uint32_t sign = bits >> 31;
    std::uint32_t exponent = (bits >> 23) & 0xFF;
    std::uint32_t mantissa = bits & 0x7F'FFFF;
    std::println("{:032b}", bits);
    std::println("sign {} exponent {} mantissa {:023b}", sign, exponent,
                 mantissa);
    std::println("power of two: {}", static_cast<int>(exponent) - 127);

    Output

    11000000110010000000000000000000
    sign 1 exponent 129 mantissa 10010000000000000000000
    power of two: 2

    6.25 is 4 × 1.5625, and 1.5625 in binary is 1.1001. So the exponent is 2 (stored as 129) and the mantissa starts with 1001. Equal numbers don’t always have equal bits: 0.0f and -0.0f differ in the sign bit, yet == says they’re equal. Compare floats as numbers, and look at their bits only when the bits are what you need.

    A double has the same three fields with 1, 11 and 52 bits. AI models often store numbers in smaller formats, 16 or even 8 bits, by cutting down these fields; Quantization builds on this layout.

    Endianness: the order of the bytes

    A std::uint32_t is 4 bytes, and the CPU has to put them in memory in some order. x86-64, and almost every Arm system, puts the lowest byte first: that’s little-endian. A few CPUs, such as IBM mainframes, and many file formats and network protocols put the highest byte first: big-endian. std::bit_cast to an array of 4 bytes shows the order in memory:

    #include <array>
    #include <bit>
    #include <cstdint>
    #include <print>
    
    std::uint32_t value = 0x1234'5678;
    auto bytes = std::bit_cast<std::array<std::uint8_t, 4>>(value);
    std::println("{::02x}", bytes);
    std::println("little-endian: {}",
                 std::endian::native == std::endian::little);
    std::println("{:#010x}", std::byteswap(value));

    Output

    [78, 56, 34, 12]
    little-endian: true
    0x78563412
    0x12345678 as a std::uint32_t in memory
    0x12345678 as a std::uint32_t in memory: each row is one value; each cell's width is its size in bytes.
    Value0123Size
    little-endian781 byte561 byte341 byte121 byte4 bytes
    big-endian121 byte341 byte561 byte781 byte4 bytes

    Little-endian (x86-64) stores the bytes 78, 56, 34, 12 at addresses 0 to 3. Big-endian stores 12, 34, 56, 78.

    {::02x} formats each element of a range with 02x. std::endian::native (from <bit>) is std::endian::little or std::endian::big, known at compile time. std::byteswap (C++23) reverses the bytes; swapping twice gives back the original.

    Inside one program, byte order never matters: you read and write whole numbers, and the CPU is consistent. It matters when bytes cross a boundary: a binary file, a network packet, or memory shared with another device.

    Reading a binary format

    A binary file format fixes the byte order of every number in it. PNG images, for example, store numbers big-endian. Bytes 16 to 23 of a PNG file hold the image’s width and height, 4 bytes each. The portable way to read such a number is to build it from its bytes with shifts. It gives the same result on any machine, because it never depends on how the CPU stores a std::uint32_t:

    #include <array>
    #include <cstdint>
    #include <print>
    #include <span>
    
    std::uint32_t read_u32_be(std::span<const std::uint8_t> b) {
        return (std::uint32_t{b[0]} << 24) | (std::uint32_t{b[1]} << 16) |
               (std::uint32_t{b[2]} << 8) | std::uint32_t{b[3]};
    }
    
    int main() {
        // The first 24 bytes of a PNG file
        std::array<std::uint8_t, 24> header = {
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // signature
            0x00, 0x00, 0x00, 0x0D, 'I',  'H',  'D',  'R',  // length, type
            0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0xE0, // width, height
        };
        std::span<const std::uint8_t> bytes = header;
        std::uint32_t width = read_u32_be(bytes.subspan(16, 4));
        std::uint32_t height = read_u32_be(bytes.subspan(20, 4));
        std::println("{} x {}", width, height);
    }

    Output

    640 x 480

    Each byte is converted to std::uint32_t before it’s shifted. Without that, integer promotion would make it an int, and 0x89 << 24 would be a negative int; converting first keeps every step unsigned. For a little-endian format, reverse the indexes: b[0] is the lowest byte. In a real program the bytes come from a file opened with std::ios::binary; Reading FASTA and FASTQ covers reading files.

    The other way is to copy the 4 bytes into a std::uint32_t with std::memcpy. The copy keeps the file’s byte order, so on a little-endian machine you swap the bytes afterwards:

    #include <array>
    #include <bit>
    #include <cstdint>
    #include <cstring>
    #include <print>
    
    std::array<std::uint8_t, 4> field = {0x00, 0x00, 0x02, 0x80};
    std::uint32_t width = 0;
    std::memcpy(&width, field.data(), sizeof width);
    std::println("copied:  {:#010x} {}", width, width);
    if constexpr (std::endian::native == std::endian::little) {
        width = std::byteswap(width);
    }
    std::println("swapped: {:#010x} {}", width, width);

    Output

    copied:  0x80020000 2147614720
    swapped: 0x00000280 640

    if constexpr (constexpr) picks the branch while compiling, so a big-endian machine skips the swap. The first line is the classic byte-order bug: no error, just a wrong number. A huge or nonsense number read from a file usually means the byte order is wrong.

    Which one should I use?

    WhatWhenWhyHow
    <bit> functionsCounting set bits, finding the lowest or highest one, checking for a power of two, rotating.One call says what you mean, and it compiles to a single instruction where the CPU has one.std::popcount(a ^ b)
    std::bitset<N>A fixed number of yes/no values that you’d rather name than mask.Named operations instead of masks, and it can hold more than 64 bits.seen.set(3); seen.count()
    std::bit_castSeeing or building the bits of a float, or any value as another type of the same size.Defined behavior, checked sizes, works in constexpr. std::memcpy is the pre-C++20 way.std::bit_cast<std::uint32_t>(f)
    Shifts on bytesReading or writing numbers in a file or network format.Correct on every machine, whatever its byte order.(std::uint32_t{b[0]} << 24) | …

    Rule of thumb: never cast a pointer to read bits as another type. Use std::bit_cast for whole values, and build numbers from bytes with shifts when a format fixes the byte order.

    Under the hood

    None of these cost what they look like. std::bit_cast and std::memcpy compile to the same single instruction that moves the float’s register into an integer register:

    #include <bit>
    #include <cstdint>
    #include <cstring>
    
    std::uint32_t bits_by_cast(float f) {
        return std::bit_cast<std::uint32_t>(f);
    }
    
    std::uint32_t bits_by_copy(float f) {
        std::uint32_t bits;
        std::memcpy(&bits, &f, sizeof bits);
        return bits;
    }

    Assembly (GCC 15, -O2)

    bits_by_cast(float):
        movd    eax, xmm0
        ret
    bits_by_copy(float):
        movd    eax, xmm0
        ret

    The compiler also recognizes the shift-and-OR pattern of read_u32_be (here taking a plain pointer to the bytes): it loads all 4 bytes at once (mov) and reverses them with one bswap instruction.

    #include <cstdint>
    
    std::uint32_t read_u32_be(const std::uint8_t* b) {
        return (std::uint32_t{b[0]} << 24) | (std::uint32_t{b[1]} << 16) |
               (std::uint32_t{b[2]} << 8) | std::uint32_t{b[3]};
    }

    Assembly (GCC 15, -O2)

    read_u32_be(unsigned char const*):
        mov     eax, DWORD PTR [rdi]
        bswap   eax
        ret

    std::popcount is one instruction only if the compiler may use the CPU’s popcnt instruction. The oldest x86-64 CPUs don’t have it, so by default GCC calls a library function (__popcountdi2) that counts in software. -mpopcnt allows the instruction (so does -march=native, on a machine that has it):

    #include <bit>
    #include <cstdint>
    
    int distance(std::uint64_t a, std::uint64_t b) {
        return std::popcount(a ^ b);
    }

    Assembly (GCC 15, -O2 -mpopcnt)

    distance(unsigned long, unsigned long):
        xor     rdi, rsi
        xor     eax, eax
        popcnt  rax, rdi
        ret

    Common pitfalls

    Bit functions on a signed type

    The <bit> functions accept only unsigned integer types. For a signed number, what the “bits” mean for a negative value would be easy to get wrong, so they refuse:

    #include <bit>
    #include <print>
    
    int flags = 0b1011;
    std::println("{}", std::popcount(flags));

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:5:33: error: no matching function for call to ‘popcount(int&)’
        5 | std::println("{}", std::popcount(flags));
          |                    ~~~~~~~~~~~~~^~~~~~~
    main.cpp:5:33: note: there is 1 candidate
    In file included from main.cpp:1:
    /usr/include/c++/15/bit:443:5: note: candidate 1: ‘template<class _Tp>  requires  __unsigned_integer<_Tp> constexpr int std::popcount(_Tp)’
          | popcount(_Tp __x) noexcept
          | ^~~~~~~~
    /usr/include/c++/15/bit:443:5: note: template argument deduction/substitution failed:
    /usr/include/c++/15/bit:443:5: note: constraints not satisfied
    /usr/include/c++/15/bit: In substitution of ‘template<class _Tp>  requires  __unsigned_integer<_Tp> constexpr int std::popcount(_Tp) [with _Tp = int]’:
    main.cpp:5:33:   required from here
        5 | std::println("{}", std::popcount(flags));
          |                    ~~~~~~~~~~~~~^~~~~~~
    /usr/include/c++/15/bit:397:13:   required for the satisfaction of ‘__unsigned_integer<_Tp>’ [with _Tp = int]
    /usr/include/c++/15/bit:397:62: note: the expression ‘std::__is_unsigned_integer<_Tp>::value [with _Tp = int]’ evaluated to ‘false’
          | concept __unsigned_integer = __is_unsigned_integer<_Tp>::value;
          |                                                          ^~~~~

    The fix is an unsigned type: unsigned int flags, or std::popcount(static_cast<unsigned int>(flags)).

    Reading a number from a byte buffer through a cast pointer

    It’s tempting to point a std::uint32_t* into a buffer of bytes. Besides breaking the strict aliasing rule, the address may not be a multiple of 4, which a std::uint32_t requires. UndefinedBehaviorSanitizer catches that one:

    #include <array>
    #include <cstdint>
    #include <print>
    
    alignas(4) std::array<std::uint8_t, 8> buffer = {1, 0, 0, 0, 2, 0, 0, 0};
    auto* field = reinterpret_cast<const std::uint32_t*>(buffer.data() + 1);
    std::uint32_t value = *field;
    std::println("{}", value);

    This fails when it runs

    main.cpp:7:23: runtime error: load of misaligned address 0x… for type 'const unsigned int', which requires 4 byte alignment
    0x…: note: pointer points here
     00 00 00  01 00 00 00 02 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 c0 ae 8a cd
                  ^

    The fix is std::memcpy into a std::uint32_t variable, or shifts, as in Reading a binary format. Both work at any address.

    Try it yourself

    Try it yourself

    A sensor sends a float as 4 bytes, highest byte first. Turn the bytes into a std::uint32_t with shifts, then into a float with std::bit_cast, and print both.

    #include <array>
    #include <bit>
    #include <cstdint>
    #include <print>
    
    int main() {
        std::array<std::uint8_t, 4> bytes = {0x40, 0x49, 0x0F, 0xDB};
        std::uint32_t bits = 0;
        float value = 0.0f;
        std::println("{:#010x} {}", bits, value);
    }

    Expected output

    0x40490fdb 3.1415927
    Show a hint

    Build bits from the four bytes with shifts: bytes[0] goes in the top 8 bits. Then std::bit_cast<float>(bits) turns the bits into a float.

    Show a solution
    #include <array>
    #include <bit>
    #include <cstdint>
    #include <print>
    
    int main() {
        std::array<std::uint8_t, 4> bytes = {0x40, 0x49, 0x0F, 0xDB};
        std::uint32_t bits =
            (std::uint32_t{bytes[0]} << 24) | (std::uint32_t{bytes[1]} << 16) |
            (std::uint32_t{bytes[2]} << 8) | std::uint32_t{bytes[3]};
        float value = std::bit_cast<float>(bits);
        std::println("{:#010x} {}", bits, value);
    }

    The bytes are big-endian, so bytes[0] (0x40) is the highest byte: shifting each byte into place gives 0x40490fdb on any machine. std::bit_cast<float> reinterprets those 32 bits as a float, which is the float nearest to pi.

    Saved in this browser only.