Skip to content
systemcoding.dev
Virtualization

Binary, Hex and Bit Masks: The Math Every Emulator Author Needs

The number systems and bit operations behind every emulator: binary, hex, shifts, AND, OR, XOR, masks, signed bytes and sign extension, with C examples.

8 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the QEMU, C and Python logos.

Every emulator is, underneath, a program that manipulates bits. An opcode is a pattern of bits that selects an instruction. A flag register is a byte where each bit means something. A pixel on an old display is a single bit in a byte. If you are comfortable with binary and hexadecimal and know five operators, you can read any processor manual and turn it into code. If you are not, every instruction will feel like a puzzle. This post teaches exactly the mathematics an emulator author uses, in C, with small examples whose output is shown: number bases, bit positions, the shift, AND, OR, XOR and NOT operators, masks, two's complement, sign extension and the traps that integer promotion sets. It assumes you can write a C program with printf and nothing else. Examples use C11 and compile with GCC 14 or Clang 19.

Why bits, and why hex

A computer stores everything as bits, each 0 or 1. Eight bits make a byte, which holds a value from 0 to 255. Humans find long strings of zeros and ones unreadable, so we group them. Hexadecimal, base 16, uses the digits 0 to 9 and the letters A to F for values ten to fifteen, and it has a property that matters: one hex digit is exactly four bits, a nibble. A byte is therefore exactly two hex digits, and a 16-bit value is exactly four.

BinaryHexDecimal
000000
000111
100199
1010A10
1111F15

To convert, split a binary number into groups of four from the right and translate each. The byte 1011 0110 is B6. Going the other way, 3C is 0011 1100. In C, you write hex with a 0x prefix and binary with 0b in GCC and Clang, which accept it as an extension and which C23 standardizes. This guide uses hex in code because it is the standard notation in processor manuals.

bases.cc
#include <stdio.h>

int main(void)
{
    unsigned value = 0xB6;
    printf("hex     0x%02X\n", value);
    printf("decimal %u\n", value);
    printf("binary  ");
    for (int bit = 7; bit >= 0; bit--)
        putchar((value >> bit) & 1 ? '1' : '0');
    putchar('\n');
    return 0;
}
Text
hex     0xB6
decimal 182
binary  10110110

The loop prints bits from position 7, the most significant, down to position 0, the least significant. Bit positions are numbered from the right starting at zero, so bit 7 of a byte is worth 128 and bit 0 is worth 1. Processor manuals use that numbering throughout.

The five operators

C has six bitwise operators, and an emulator uses all of them constantly. Learn each as an operation on every bit position at once.

AND (&) gives 1 only where both inputs are 1. Its job is to extract or test bits: ANDing with a mask keeps the bits where the mask has a 1 and clears the rest.

OR (|) gives 1 where either input is 1. Its job is to set bits and to combine values.

XOR (^) gives 1 where the inputs differ. Its job is to toggle bits, and drawing on a screen by XOR is how CHIP-8 sprites work.

NOT (~) flips every bit. In C it applies to the whole width of the promoted type, so mask the result back to the size you want.

Shift left (<<) moves bits towards the high end, filling with zeros, and each shift left multiplies an unsigned value by two. Shift right (>>) moves them down and divides by two for unsigned values.

A short table of examples with one byte, x = 0xB6 (1011 0110):

ExpressionBinary resultHexWhat it does
x & 0x0F0000 011006Keep the low nibble
x & 0xF01011 0000B0Keep the high nibble
`x \0x01`1011 0111B7Set bit 0
x ^ 0xFF0100 100149Flip all eight bits
x >> 40000 10110BMove the high nibble down
x << 10110 1100 (after masking to 8 bits)6CDouble, losing the top bit

The last row shows the first trap: shifting left can push bits off the end of a byte. In C the result of x << 1 for a byte promoted to int is 0x16C, and it only becomes 0x6C after you store it in an 8-bit variable or mask with 0xFF. Emulators mask deliberately.

Masks and shifts together: extracting fields

Real instruction formats pack several fields into one word, and the standard way to extract a field is shift, then mask. To get a field that starts at bit lo and is width bits wide:

field = (word >> lo) & ((1 << width) - 1)

The expression (1 << width) - 1 builds a mask of width ones: for width 4 it is 0xF, for width 12 it is 0xFFF. In a macro or function it keeps decoding uniform.

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

static inline unsigned field(uint32_t word, unsigned lo, unsigned width)
{
    return (word >> lo) & ((1u << width) - 1u);
}

int main(void)
{
    uint16_t instr = 0xD125;                 /* a CHIP-8 draw instruction */
    printf("op = %X\n", field(instr, 12, 4));
    printf("x  = %X\n", field(instr, 8, 4));
    printf("y  = %X\n", field(instr, 4, 4));
    printf("n  = %X\n", field(instr, 0, 4));
    return 0;
}
Text
op = D
x  = 1
y  = 2
n  = 5

Reading 0xD125 as four hex digits already gives you the four fields, which is the benefit of hex. The function does the same job for fields that do not line up with nibble boundaries, as RISC-V's do, where a register number is five bits wide starting at bit 7.

Setting, clearing and testing single bits

Flag registers need three operations on one bit. With bit position n:

  • Set: flags |= (1u << n)

  • Clear: flags &= ~(1u << n)

  • Test: (flags >> n) & 1

  • Toggle: flags ^= (1u << n)

A processor with a status byte where bit 7 is negative, bit 1 is zero and bit 0 is carry gets symbolic names, so that the code reads like the manual:

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

#define FLAG_CARRY    (1u << 0)
#define FLAG_ZERO     (1u << 1)
#define FLAG_NEGATIVE (1u << 7)

int main(void)
{
    uint8_t status = 0;
    status |= FLAG_ZERO;                 /* set zero */
    status |= FLAG_CARRY;                /* set carry */
    status &= (uint8_t)~FLAG_ZERO;       /* clear zero */
    printf("status = 0x%02X\n", status);
    printf("carry set? %s\n", (status & FLAG_CARRY) ? "yes" : "no");
    printf("negative set? %s\n", (status & FLAG_NEGATIVE) ? "yes" : "no");
    return 0;
}
Text
status = 0x01
carry set? yes
negative set? no

Note the cast on ~FLAG_ZERO. The ~ operator works on an unsigned int, so the result has 32 bits, and the cast brings it back to the byte before the compound assignment. Without the cast most compilers still produce the right answer for this particular case, but the habit protects you in places where it matters.

Signed numbers and two's complement

A byte can hold 0 to 255, or, if the processor treats it as signed, -128 to 127. Almost all hardware uses two's complement: the top bit is the sign, and to negate a number you invert every bit and add one. The byte 0xFF is 255 unsigned and -1 signed. The byte 0x80 is 128 unsigned and -128 signed.

The important fact for emulators is that the same bits are interpreted differently by different instructions. An add instruction produces the same bit pattern for signed and unsigned operands, and only the flags differ. A relative branch reads its offset as signed, so an offset byte of 0xFB means -5, a jump back five bytes. To read it correctly in C, convert through a signed type of the same size:

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

int main(void)
{
    uint8_t raw = 0xFB;
    int8_t  offset = (int8_t)raw;       /* reinterpret as signed */
    uint16_t pc = 0x0200;

    printf("raw=%u signed=%d\n", raw, offset);
    printf("pc + offset = 0x%04X\n", (uint16_t)(pc + offset));
    return 0;
}
Text
raw=251 signed=-5
pc + offset = 0x01FB

The cast (int8_t)raw is implementation-defined in C when the value does not fit, but every compiler you will use on a modern system defines it as the two's complement reinterpretation, and C23 makes that the rule.

Sign extension

Widening a signed value must preserve its meaning. Turning the 8-bit 0xFB (-5) into a 16-bit value should give 0xFFFB, not 0x00FB. This is sign extension: copy the top bit into all the new upper bits. In C you get it by converting through the signed type:

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

int main(void)
{
    uint8_t  b = 0xFB;
    uint16_t zero_extended = b;                    /* 0x00FB */
    uint16_t sign_extended = (uint16_t)(int16_t)(int8_t)b;   /* 0xFFFB */
    printf("zero: 0x%04X  sign: 0x%04X\n", zero_extended, sign_extended);
    return 0;
}
Text
zero: 0x00FB  sign: 0xFFFB

RISC-V immediates, ARM offsets and 6502 branches all need sign extension. For a field narrower than a standard type, such as a 12-bit immediate, the trick is to shift it to the top of a 32-bit word and shift back with an arithmetic shift: ((int32_t)(x << 20)) >> 20. Right-shifting a negative signed value is implementation-defined in older C but is an arithmetic shift on every mainstream compiler.

Integer promotion, the quiet trap

In C, operands smaller than int are promoted to int before arithmetic. A uint8_t added to a uint8_t produces an int, so 200 + 100 is 300, not 44. The wrap-around only happens when you store the result back into an 8-bit variable. That is helpful when you want to see the carry, as in unsigned sum = a + b; carry = sum > 0xFF;, and harmful when you forget it.

A related trap is the comparison of a promoted uint8_t with a negative int, and the left shift of a value into the sign bit of int, which is undefined behaviour for signed types in older C standards. Use unsigned types in bit manipulation and cast explicitly at boundaries.

Endianness: byte order

A 16-bit value occupies two bytes, and the order in which they sit in memory is endianness. A little-endian machine such as the 6502 and x86 stores the least significant byte at the lower address. A big-endian machine such as CHIP-8's instruction format stores the most significant byte first. The 16-bit value 0x1234 at address 100 is 34 at 100 and 12 at 101 on a little-endian machine.

You assemble multi-byte values explicitly from bytes, so the host's own endianness never matters:

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

int main(void)
{
    const uint8_t mem[] = { 0x34, 0x12 };
    uint16_t little = (uint16_t)(mem[0] | (mem[1] << 8));
    uint16_t big    = (uint16_t)((mem[0] << 8) | mem[1]);
    printf("little-endian read: 0x%04X\n", little);
    printf("big-endian read:    0x%04X\n", big);
    return 0;
}
Text
little-endian read: 0x1234
big-endian read:    0x3412

Never read a 16-bit value by casting a uint8_t * to uint16_t *. It depends on the host's byte order and on alignment, and an emulator that does it breaks on a machine of the other kind.

A quick reference for emulator work

Keep these patterns near you while you work.

  • Extract a field: (word >> lo) & mask.

  • Test a bit: (value >> n) & 1.

  • Set, clear, toggle: |=, &= ~, ^= with 1u << n.

  • Wrap to 8 bits: (uint8_t)expr or expr & 0xFF; to 16 bits: (uint16_t)expr.

  • Carry from an 8-bit add: compute in unsigned and test > 0xFF.

  • Reinterpret as signed: (int8_t)byte, then widen.

  • Build a 16-bit value from bytes: lo | (hi << 8) for little-endian.

Taggedcbeginner
Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.