Number Systems & Data Representation

Inspect binary and hexadecimal values, fixed-width integers, floating-point rounding, byte order, and character encodings in real programs.

published: reading time: 31 min read author: Geek Workbench
Quick Summary

Inspect binary and hexadecimal values, fixed-width integers, floating-point rounding, byte order, and character encodings in real programs.

Introduction

Computers store data as bits, but a bit pattern has no meaning without a type, width, and byte order. The same eight bits can represent an unsigned value, a signed value, or part of a floating-point number. These examples show how to inspect what a program actually stores.

The distinction matters in ordinary code: integer conversions can lose range, floating-point values round, and serialized bytes have an order. I use C, JavaScript, and Python below, and name the type whenever the rules differ.

When to use this knowledge

Apply your understanding of data representation when:

  • Debugging numerical precision issues in financial or scientific calculations
  • Writing code that manipulates binary protocols or file formats
  • Interpreting crash dumps and core files
  • Working with bitwise operations for flags and masks
  • Understanding why 0.1 + 0.2 != 0.3 in floating-point
  • Ensuring cross-platform compatibility for integer sizes

Skip the deep dive if:

  • You’re exclusively using high-level languages with arbitrary precision libraries
  • You never touch network protocols, binary files, or hardware registers

Architecture diagram

One path from input characters to arithmetic operations:

flowchart LR
    A[User Input: -123.456] --> B[ASCII Characters]
    B --> C[Binary Encoding]
    C --> D[IEEE 754 Single Precision]
    D --> E[Hexadecimal: 0xC2F6E979]
    E --> F[Memory Layout]
    F --> G[Registers]
    G --> H[ALU Operations]

Core concepts

Binary: the foundation

Binary is a base-2 number system using only digits 0 and 1. Each position represents a power of 2, reading right to left: 1, 2, 4, 8, 16, 32, 64, 128, 256, and so forth.

The binary number 1101 equals: 1×8 + 1×4 + 0×2 + 1×1 = 13

Digital circuits can distinguish two voltage ranges more reliably than many closely spaced levels. Binary maps those ranges to 0 and 1.

Binary was not the only option explored in early computing, but it fits transistor circuits well. A circuit has a noise margin: a range of voltages that it can reliably read as 0 or 1. Ten distinct levels would need tighter tolerances, so noise could make one digit look like another.

In the byte 0b10110101, the set bits contribute 128 + 32 + 16 + 4 + 1, so its unsigned value is 181. The same positional rule works at any width; a 16-bit value simply has eight more bit positions than a byte.

Sampling rate and bit depth describe different limits. The Nyquist-Shannon theorem relates sample rate to the highest signal frequency; bit depth sets the number of quantization levels. For an ideal converter, each additional bit adds about 6 dB of dynamic range. Real converters also have noise and other limits.

Hexadecimal: a compact way to write bits

Hexadecimal (base-16) provides a more compact notation for binary data. Each hex digit represents exactly 4 binary bits, and hex digits 0-9, A-F map to decimal 10-15.

Binary: 1111 0101 1010 0011
Hex:    F    5    A    3

Hex is preferred for:

  • Memory addresses (which are often aligned to 4 or 8 bytes)
  • Machine code opcodes
  • Bit masks and flags
  • Color codes in web development (though that uses hex for RGB values)

Each hexadecimal digit maps to four bits: A is 1010, and F is 1111. To convert binary to hex, group bits in fours from the right and pad the leftmost group with zeroes if needed. Two hex digits fit neatly in one 8-bit byte.

This also makes hex dumps easier to scan: a 32-bit value takes eight hex digits, and a 64-bit value takes sixteen. For example, 0x80 0x00 0x00 0x00 has the high bit set in its first displayed byte. Whether that byte is first in memory depends on the format’s byte order.

Some patterns are worth recognizing: 0xFF has all eight bits set, 0x00 has none, and 0x7F800000 is positive infinity in IEEE 754 binary32. The meaning of a hex value still depends on its type and format.

Signed integers: sign-and-magnitude and two’s complement

Computers need to represent negative numbers. Two common schemes are:

Sign-and-magnitude uses the leftmost bit as a sign (0 for positive, 1 for negative) and the rest for the magnitude. In 8 bits, 10000001 is -1 and 00000001 is +1. It has two representations of zero, +0 and -0.

Two’s complement is the representation used by C’s exact-width signed integer types when those types are provided. To form a negative value, invert the bits of its positive magnitude and add 1. An 8-bit signed value ranges from -128 to +127, so the range has one more negative value than positive values.

The example uses C’s int8_t and uint8_t types from <stdint.h>. These exact-width types are optional; use them only when the implementation provides them. uint8_t conversion is modulo 256. That makes converting a negative int8_t value to uint8_t a defined way to inspect its corresponding 8-bit pattern.

// C: inspect the 8-bit representation of a signed value
#include <stdio.h>
#include <stdint.h>

static void print_binary(uint8_t value) {
    for (int i = 7; i >= 0; i--) {
        printf("%d", (value >> i) & 1);
        if (i == 4) printf(" ");  // Separate nibbles
    }
}

int main(void) {
    int8_t positive = 42;
    int8_t negative = -42;
    uint8_t negative_bits = (uint8_t)negative;

    printf("int8_t +42: %d\n", positive);
    printf("int8_t -42: %d\n", negative);
    printf("uint8_t view of -42: ");
    print_binary(negative_bits);
    printf(" (0x%02X)\n", (unsigned)negative_bits);
    printf("sum after integer promotion: %d\n", positive + negative);

    return 0;
}

The output for negative_bits is 1101 0110 (0xD6). The int8_t values are promoted to int before addition, so the final sum is 0. This is not signed overflow.

Fixed-width overflow depends on the operation

In C, unsigned conversion wraps modulo the destination range. Signed overflow does not: overflowing a signed arithmetic operation has undefined behavior. Small unsigned types are also promoted before arithmetic, then converted back when assigned:

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

int main(void) {
    uint8_t count = 250;
    int promoted_sum = count + 10;       // int: 260
    uint8_t stored = (uint8_t)promoted_sum; // uint8_t conversion: 4 modulo 256

    printf("promoted sum: %d\n", promoted_sum);
    printf("stored uint8_t: %u\n", (unsigned)stored);
}

Do not use INT_MAX + 1 as a wrapping example in C. If the result is outside the signed type’s range, the behavior is undefined; it is not a portable way to obtain INT_MIN.

Biased representation is used for floating-point exponents. IEEE 754 binary32 stores an 8-bit exponent with a bias of 127; binary64 uses an 11-bit exponent with a bias of 1023.

Floating-point: approximating real numbers

Values such as pi and one tenth cannot be represented exactly with a finite binary fraction. Floating-point stores a rounded approximation using a sign, exponent, and fraction field.

IEEE 754 single-precision (32-bit) format:

  • 1 bit: Sign (0 = positive, 1 = negative)
  • 8 bits: Exponent (biased by 127)
  • 23 bits: Fraction field (the leading 1 is implicit for normal values)
Sign (1) | Exponent (8) | Mantissa (23)
   S     |   EEEEEEEE   |   MMMM...MMM

For normal values, the represented value is (-1)^S × 1.M × 2^(E-bias).

Special values exist:

  • Zero: all exponent and mantissa bits are 0 (sign bit determines +0 or -0)
  • Infinity: all exponent bits are 1, mantissa is 0
  • NaN (Not a Number): all exponent bits are 1, mantissa is non-zero
  • Subnormal values: all exponent bits are 0 and the fraction field is non-zero; these have reduced precision near zero

The next Python example asks struct to pack 0.1 as IEEE 754 binary32 in little-endian order. The Python float input is converted to that 32-bit format; it is not itself a 32-bit float. The printed bytes and decoded value show the rounding directly:

import struct

value = 0.1
packed = struct.pack("<f", value)       # IEEE 754 binary32, little-endian
bits, = struct.unpack("<I", packed)     # Read those same bytes as uint32
rounded, = struct.unpack("<f", packed)  # Decode the stored binary32 value

print(packed.hex(" "))       # cd cc cc 3d
print(f"0x{bits:08x}")        # 0x3dcccccd
print(repr(rounded))          # 0.10000000149011612

JavaScript uses one Number type for numeric literals and arithmetic. It is IEEE 754 binary64, with exact safe integers from -(2**53 - 1) through 2**53 - 1. JavaScript bitwise operators are a separate case: they convert Number operands to 32-bit integers. Use BigInt for integer arithmetic outside the safe range, and do not mix BigInt and Number in an operation.

console.log(0.1 + 0.2); // 0.30000000000000004
console.log(Number.isSafeInteger(2 ** 53)); // false
console.log(2 ** 31, (2 ** 31) | 0); // 2147483648, -2147483648
console.log(9007199254740992 === 9007199254740993); // true
console.log(9007199254740993n + 1n); // 9007199254740994n

Byte order is separate from the number’s value

Endianness describes how a multi-byte value is laid out as bytes. It does not change the numeric value. This Python exercise serializes the same 32-bit unsigned integer in both byte orders:

import struct

value = 0x12345678
print(struct.pack(">I", value).hex(" "))  # 12 34 56 78 (big-endian)
print(struct.pack("<I", value).hex(" "))  # 78 56 34 12 (little-endian)

The > and < prefixes make byte order explicit, so the result does not depend on the machine running Python. Use the byte order required by the file format or network protocol when serializing data.

Character encodings

Text encodings map characters to code points and bytes. Here are the main terms used in the examples:

ASCII (American Standard Code for Information Interchange) — 7 bits, 128 characters. Uppercase A-Z is 65-90, lowercase a-z is 97-122, digits 0-9 are 48-57. Control characters (0-31) handle things like newline and carriage return.

ISO-8859-1 (Latin-1) — 8 bits, 256 characters. Adds characters needed for Western European languages. First 128 match ASCII.

Unicode — Assigns code points written as U+XXXX, from U+0000 to U+10FFFF. A visible character can use one code point or a sequence of code points.

UTF-8 — Variable-width encoding for Unicode. ASCII characters (U+0000 to U+007F) use 1 byte. Other characters use 2-4 bytes. UTF-8 is the dominant encoding on the web and in Linux/Unix systems.

Character | Unicode | UTF-8 bytes
----------|---------|-------------
A         | U+0041  | 41
€         | U+20AC  | E2 82 AC
😀        | U+1F600 | F0 9F 98 80
// Demonstrating character encoding handling in C
#include <stdio.h>
#include <uchar.h>
#include <string.h>

// Count code points in a valid, NUL-terminated UTF-8 string
size_t utf8_strlen(const char *s) {
    size_t count = 0;
    const unsigned char *p = (const unsigned char *)s;

    while (*p) {
        // Count characters, not bytes
        if ((*p & 0x80) == 0) {
            // 1-byte character (ASCII)
            p += 1;
        } else if ((*p & 0xE0) == 0xC0) {
            // 2-byte character
            p += 2;
        } else if ((*p & 0xF0) == 0xE0) {
            // 3-byte character
            p += 3;
        } else if ((*p & 0xF8) == 0xF0) {
            // 4-byte character
            p += 4;
        }
        count++;
    }
    return count;
}

int main() {
    const char *text = "Hello, world! 😀";
    printf("String: %s\n", text);
    printf("Bytes: %zu\n", strlen(text));
    printf("Characters: %zu\n", utf8_strlen(text));

    return 0;
}

Production failure scenarios

Scenario 1: Ariane 5 flight 501

What happened: On June 4, 1996, Ariane 5 flight 501 broke apart 37 seconds after launch. An inertial reference system tried to convert a floating-point horizontal velocity value to a signed 16-bit integer. The value was outside the range -32,768 to 32,767, so the conversion raised an exception the system did not handle.

Root cause: Ariane 5 could reach horizontal velocities that the reused Ariane 4 software had not encountered. The conversion was not needed after liftoff, but the code still ran.

Mitigation: Check that a value fits before converting it. Here is a C example using optional exact-width integer types:

#include <stdbool.h>
#include <stdint.h>

bool safe_int32_from_int64(int64_t value, int32_t *out) {
    if (value < INT32_MIN || value > INT32_MAX) {
        return false;
    }
    *out = (int32_t)value;
    return true;
}

Scenario 2: Rounding in financial calculations

Binary floating-point can represent some decimal fractions exactly, but not 0.1. For example, JavaScript Number stores 0.1 as a nearby binary64 value, so 0.1 + 0.2 evaluates to 0.30000000000000004. Rounding at each operation can accumulate or cancel; the result depends on the calculation.

This behavior alone does not explain any particular financial loss. It does mean software should use arithmetic that matches its rules. For amounts in cents, C’s optional int64_t can represent each cent exactly if the amount and intermediate results fit; division still needs an explicit rounding rule. Python’s Decimal is another option when the business rules use decimal fractions. Decide how to round interest, tax, and exchange-rate calculations, then test those rules with values near boundaries.

Scenario 3: The Year 2038 problem

On systems where time_t is a signed 32-bit count of seconds since 1970-01-01, the largest timestamp is 2038-01-19 03:14:07 UTC. The next second is outside that type’s range. The C and POSIX environment determines the actual time_t type, so this is a risk for systems that use the 32-bit form, not every 32-bit machine.

Use a platform’s 64-bit time interface when it is available, and check the documented time_t width and ABI for each target. Avoid assuming that a compiler flag or CPU word size alone changes the type.

Trade-off table

Representation Range Precision Storage Use case
C uint8_t 0 to 255 Exact 8 bits Flags, small counters
C int32_t -2,147,483,648 to 2,147,483,647 Exact 32 bits Counts with a bounded range
IEEE 754 binary32 About ±3.4 × 10^38 About 7 decimal digits 32 bits Approximate values with limited storage
IEEE 754 binary64 About ±1.8 × 10^308 About 15–17 decimal digits 64 bits General floating-point calculations
JavaScript Number Finite values up to about ±1.8 × 10^308; safe integers are -(2^53-1) through +(2^53-1) Binary64 precision 64 bits General JavaScript numeric values
C int64_t -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Exact 64 bits Large counts, bounded timestamps

C’s exact-width typedefs are optional. The IEEE rows name formats, not C types: the C standard does not require every float or double implementation to use these formats.

Implementation snippets

Bit manipulation for flags

#!/usr/bin/env python3
"""
Bit manipulation utilities for flags and masks
"""

def set_bit(value: int, bit: int) -> int:
    """Set a specific bit to 1"""
    return value | (1 << bit)

def clear_bit(value: int, bit: int) -> int:
    """Set a specific bit to 0"""
    return value & ~(1 << bit)

def toggle_bit(value: int, bit: int) -> int:
    """Toggle a specific bit"""
    return value ^ (1 << bit)

def get_bit(value: int, bit: int) -> int:
    """Get the value of a specific bit (0 or 1)"""
    return (value >> bit) & 1

def is_power_of_two(n: int) -> bool:
    """Check if n is a power of two using bit trick"""
    return n > 0 and (n & (n - 1)) == 0

def count_set_bits(n: int) -> int:
    """Count the number of set bits (population count)"""
    count = 0
    while n:
        n &= n - 1  # Clear lowest set bit
        count += 1
    return count

# Example: File permission flags
READ = 0b100  # 4
WRITE = 0b010  # 2
EXECUTE = 0b001  # 1

def add_permission(perms: int, new_perm: int) -> int:
    """Add a permission using bitwise OR"""
    return perms | new_perm

def remove_permission(perms: int, rem_perm: int) -> int:
    """Remove a permission using bitwise AND with complement"""
    return perms & ~rem_perm

def has_permission(perms: int, check_perm: int) -> bool:
    """Check if a permission is set"""
    return (perms & check_perm) != 0

# Demonstration
perms = READ | WRITE  # 0b110 = 6
print(f"Initial permissions: {perms:#o} (octal), {perms:#06b} (binary)")

perms = add_permission(perms, EXECUTE)
print(f"After adding EXECUTE: {perms:#o}")

perms = remove_permission(perms, WRITE)
print(f"After removing WRITE: {perms:#o}")

print(f"Has READ? {has_permission(perms, READ)}")
print(f"Has WRITE? {has_permission(perms, WRITE)}")

Converting between bases

#!/usr/bin/env python3
"""
Number base conversion utilities
"""

def int_to_hex(n: int, width: int = 0) -> str:
    """Convert integer to hexadecimal string with optional zero-padding"""
    hex_chars = "0123456789ABCDEF"
    if n == 0:
        result = "0"
    else:
        result = ""
        while n > 0:
            result = hex_chars[n % 16] + result
            n //= 16
    return "0x" + result.zfill(width) if width > 0 else "0x" + result

def int_to_binary(n: int, width: int = 0) -> str:
    """Convert integer to binary string with optional zero-padding"""
    if n == 0:
        result = "0"
    else:
        result = ""
        while n > 0:
            result = str(n % 2) + result
            n //= 2
    return "0b" + result.zfill(width) if width > 0 else "0b" + result

def hex_to_int(hex_str: str) -> int:
    """Convert hexadecimal string to integer"""
    hex_str = hex_str.removeprefix("0x").removeprefix("0X")
    return int(hex_str, 16)

def binary_to_int(bin_str: str) -> int:
    """Convert binary string to integer"""
    bin_str = bin_str.removeprefix("0b").removeprefix("0B")
    return int(bin_str, 2)

def float_to_ieee754(value: float) -> tuple[int, int, int]:
    """Break down float into IEEE 754 components"""
    import struct

    packed = struct.pack('>f', value)
    bits = int.from_bytes(packed, 'big')

    sign = (bits >> 31) & 1
    exponent = (bits >> 23) & 0xFF
    mantissa = bits & 0x7FFFFF

    return sign, exponent, mantissa

# Demonstration
print("=== Base Conversions ===")
print(f"255 in hex: {int_to_hex(255)}")
print(f"255 in binary: {int_to_binary(255)}")
print(f"0xFF in decimal: {hex_to_int('0xFF')}")
print(f"0b1010 in decimal: {binary_to_int('0b1010')}")

print("\n=== IEEE 754 Analysis ===")
sign, exp, mant = float_to_ieee754(3.14159)
print(f"π (3.14159): sign={sign}, exponent={exp}, mantissa={mant:06x}")
print(f"Hex representation: {int_to_hex(sign << 31 | exp << 23 | mant, 8)}")

Observability checklist

When debugging data representation issues:

  • Integer overflow detection — Use the compiler’s signed-overflow sanitizer during development (for example, -fsanitize=signed-integer-overflow where supported)
  • Floating-point exception flags — Check FE_DIVBYZERO, FE_INVALID, FE_OVERFLOW after calculations
  • NaN propagation — Use isnan() and isinf() to detect special values
  • Character encoding validation — Verify strings are valid UTF-8 using iconv or similar
  • Endianness checks — Check the host with a platform API such as Python’s sys.byteorder; serialize using the format’s explicit byte order
  • Precision loss tracking — Record when an IEEE 754 binary64 value is converted to binary32

Useful diagnostic commands:

# Check for NaN and infinity in a running process
# Attach with GDB and call: isnan(), isinf()

# Hexdump to see raw memory representation
hexdump -C your_file.bin | head -20

# Check floating-point environment
python3 -c "import sys; print(sys.float_info)"

Common pitfalls

Security pitfalls

Integer overflow in buffer sizes — A size calculation can wrap before allocation, leaving a buffer smaller than the data later copied into it. The exact failure depends on the operand types and promotions. Check additions and multiplications before they are used as allocation sizes, and verify the copy length against the allocated capacity.

Format string vulnerabilities — The printf family treats its first argument as a format string. Passing untrusted input directly to printf can expose memory or cause writes through format directives on some platforms. Use a fixed format such as printf("%s", user_input).

Endianness and network protocols — Internet protocols commonly define multi-byte fields in big-endian network byte order. A host’s native byte order may differ, so convert fields as the protocol requires. In C, htons(), htonl(), ntohs(), and ntohl() handle standard 16-bit and 32-bit conversions on platforms that provide them; there is no universally portable htonll(). For other widths, use the protocol’s serialization library or write each byte explicitly.

Unicode normalization and confusables — The text “é” can be encoded as U+00E9 or as U+0065 followed by U+0301. These sequences can look the same while using different code points. Normalize text to NFC when an application needs canonically equivalent strings to compare equally; Python provides unicodedata.normalize("NFC", text), and JavaScript provides text.normalize("NFC"). Normalization does not prevent lookalike characters from different scripts, so identifier and domain checks need separate confusable-character handling.

Programming pitfalls

Pitfall: Assuming int is 32 bits In C, the width of int is implementation-defined. Write int32_t or int64_t when you need a specific width and the implementation provides that type. Some embedded targets have a 16-bit int.

Pitfall: Comparing floating-point values for equality In JavaScript, 0.1 + 0.2 === 0.3 is false because Number uses binary64. Use a tolerance only when approximate comparison matches the problem; choose it from the scale and units of the values.

Pitfall: Assuming char is signed Whether char is signed or unsigned is implementation-defined. Cast to unsigned char when you need to ensure the range 0-255.

Pitfall: Forgetting byte order in serialization Writing int directly to a file and reading on a different architecture will corrupt data. Use explicit serialization with defined byte order.

Pitfall: Treating a C byte as 8 bits In C, sizeof(char) is 1 by definition, but a byte is CHAR_BIT bits and need not be 8 on every implementation. Use uint8_t only when the implementation provides that exact-width type.

Quick recap

  • Binary (base-2) uses powers of 2; each bit represents an increasing power of 2
  • Hexadecimal (base-16) compactly represents 4 binary bits per hex digit
  • C’s optional exact-width signed integers use two’s complement; an 8-bit signed value ranges from -128 to +127
  • IEEE 754 binary32 and binary64 use sign, exponent, and fraction fields
  • IEEE 754 includes zero, infinity, NaN, and subnormal values
  • ASCII uses 128 code points; UTF-8 encodes Unicode with one to four bytes
  • C unsigned conversions use modulo arithmetic; signed overflow is undefined behavior
  • Floating-point rounding can accumulate or cancel; use arithmetic that matches the calculation’s rules
  • Always validate integer conversions and array bounds before use
  • Bit manipulation is powerful for flags, masks, and optimized code

Interview questions

1. Why can't floating-point numbers represent 0.1 exactly in binary?

In JavaScript, the number literal 0.1 is stored as an IEEE 754 binary64 Number. Since 1/10 has a factor of 5 in its denominator, its binary fraction repeats and must be rounded to a nearby representable value. The same applies to 0.2, so 0.1 + 0.2 produces 0.30000000000000004, not exactly 0.3.

2. What is the difference between big-endian and little-endian?

Endianness describes the byte order of multi-byte values in memory. In big-endian, the most significant byte comes first (at the lowest address). In little-endian, the least significant byte comes first. For a C uint32_t value 0x12345678 stored at addresses starting at 0x00, depending on byte order:

  • Big-endian: 0x00=0x12, 0x01=0x34, 0x02=0x56, 0x03=0x78
  • Little-endian: 0x00=0x78, 0x01=0x56, 0x02=0x34, 0x03=0x12

Internet protocols commonly specify big-endian network byte order. x86 processors use little-endian; ARM byte order depends on the platform and configuration. When reading a file or packet, follow its specified format instead of assuming the host's byte order.

3. Explain the IEEE 754 special values: infinity, NaN, denormals.

For IEEE 754 binary32, 0x7F800000 encodes positive infinity and 0xFF800000 encodes negative infinity. An all-ones exponent with a non-zero fraction encodes a NaN. Whether a particular division or square-root expression produces these values depends on the language and its floating-point rules.

In IEEE 754 binary32, a subnormal has an all-zero exponent and a non-zero fraction. Subnormals fill the gap between zero and the smallest normal value. Some hardware or runtime modes handle them more slowly or flush them to zero; check the platform behavior when performance or exact results depend on them.

4. What happens in a signed integer overflow?

In C, conversion to an 8-bit uint8_t is modulo 256. The operands in uint8_t a = 255; uint8_t b = (uint8_t)(a + 1); are promoted to int; the addition gives 256, then the conversion stores 0.

Signed overflow in C is undefined behavior. Do not rely on INT_MAX + 1 wrapping to INT_MIN; a compiler may optimize under the assumption that signed overflow does not occur. Check ranges before arithmetic or use an appropriate unsigned type when modulo arithmetic is intended. Compiler sanitizers can help find signed overflow during development.

5. How does UTF-8 encoding work, and why is it preferred?

UTF-8 is a variable-width encoding for Unicode using 1 to 4 bytes:

  • 1 byte: 0xxxxxxx — ASCII (U+0000 to U+007F). This means ASCII text is valid UTF-8.
  • 2 bytes: 110xxxxx 10xxxxxx — Start with 110, continuation bytes start with 10. Covers U+0080 to U+07FF.
  • 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx — Covers U+0800 to U+FFFF.
  • 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx — Covers U+10000 to U+10FFFF.

UTF-8 preserves ASCII byte values and is self-synchronizing, so a decoder can find character boundaries after starting partway through a string. ASCII U+0000 is still encoded as a zero byte, which is why C strings can use it as a terminator. Many common CJK characters use three bytes.

6. What is the difference between sign-magnitude and two's complement representation?

Sign-magnitude uses the leftmost bit as a sign flag (0 for positive, 1 for negative) and the remaining bits for magnitude. In 8-bit: +1 is 00000001, -1 is 10000001. This creates two zeros (+0 and -0), which complicates arithmetic.

For C's optional int8_t, two's complement encodes -1 as 11111111. It has one zero and an asymmetric range from -128 to +127. Hardware can use the same adder for signed and unsigned addition.

Most modern systems use two's complement because the same adder circuit handles both positive and negative addition, whereas sign-magnitude requires different logic for each case.

7. What is buffer overflow and how does integer overflow relate to it?

A buffer overflow occurs when a program accesses memory beyond an allocated buffer. An integer range error can contribute when a program calculates a buffer size incorrectly, but the details depend on the types and conversions involved.

In C, converting an out-of-range size_t value to int does not portably produce -1. The result is implementation-defined or the implementation may raise an implementation-defined signal. Check the range before conversion, and check size calculations before allocation or copying.

Mitigations include bounds checks at the point of use and development builds with compiler sanitizers.

8. Explain denormal numbers in IEEE 754 and why they matter.

For IEEE 754 binary32, subnormal numbers have an all-zero exponent and a non-zero fraction. They fill the range between zero and the smallest normal value, with the value (-1)^S × 0.F × 2^(1-bias).

Subnormals provide gradual underflow: values can get smaller than the minimum normal value instead of jumping straight to zero. Their performance varies by processor and runtime settings; some platforms flush subnormal values to zero.

9. What is the Gray code representation and why is it used in certain applications?

Gray code is a binary numeral system where two consecutive values differ in only one bit. For example, binary sequences: 000, 001, 010, 011, 100, 101, 110, 111. Gray code for same sequence: 000, 001, 011, 010, 110, 111, 101, 100.

The property of changing only one bit at a time eliminates the problem of binary counters where multiple bits can change simultaneously (e.g., 011 to 100 changes all three bits). If you sample during the transition, you might read spurious values like 001 or 010.

Uses:

  • Rotary encoders: Only one track changes at a time, reducing ambiguous readings during transitions; metastability is still possible.
  • K-maps: Gray code ordering groups minterms by adjacency, simplifying Boolean simplification
  • Error correction: In some communication systems, Gray code reduces bit error impact

To convert binary to Gray code: G = B ^ (B >> 1) (XOR with right-shifted version). To convert back: binary bit N is XOR of Gray bit N with all higher Gray bits.

10. What is the purpose of normalization in floating-point representation and how does it affect precision?

Normalization ensures the leading bit of the mantissa is always 1 (for normal numbers), maximizing the precision available in the given bit width. In IEEE 754, normalized numbers have an implicit leading 1 before the binary point: 1.M × 2^E.

For example, the number 5.0 in binary is 101.0, which normalizes to 1.01 × 2^2. The mantissa stores only the significant digits (01), while the exponent stores 2 (biased). This format achieves maximum precision—every bit of the mantissa is meaningful.

Without normalization, the same number could be represented as 0.101 × 2^3 or 10.1 × 2^1, wasting precision bits. Denormal numbers (where exponent bits are all zero but mantissa is non-zero) sacrifice this property to provide gradual underflow, but they have reduced precision compared to normalized numbers of the same size.

11. How does the IEEE 754 standard handle rounding, and what are the different rounding modes?

IEEE 754 defines rounding directions, including:

  • Nearest, ties to even: Choose the nearest representable value; an exact tie goes to the result with an even least significant bit.
  • Toward zero: Discard the fractional part toward zero, for either sign.
  • Toward positive infinity: Choose the next representable value toward +∞.
  • Toward negative infinity: Choose the next representable value toward -∞.

Python's built-in round() uses ties-to-even for exact halfway cases, such as round(2.5) == 2 and round(3.5) == 4. These examples use Python integers after rounding; they do not change the rounding mode for Python's floating-point arithmetic.

C provides fesetround() in <fenv.h>, but whether generated code observes the selected mode depends on the implementation and compiler settings. For decimal business rules, Python's Decimal supports explicit rounding modes.

12. What is the difference between BCD (Binary-Coded Decimal) and binary integer representation?

BCD (Binary-Coded Decimal) encodes each decimal digit (0-9) in its own 4-bit binary representation. For example, the decimal number 59 is stored as 0101 1001 (0x59), not the binary 00111011 (0x3B).

BCD stores decimal digits directly, so values with a chosen decimal scale can avoid binary-fraction rounding. The scale and arithmetic rules come from the specific format or application.

BCD disadvantages:

  • Wasteful: 4 bits can represent 0-15, but BCD only uses 0-9
  • Arithmetic operations are more complex (need adjustment after each digit addition)
  • Less efficient storage than binary

Many IBM mainframes and embedded systems still use BCD for financial calculations. The packed BCD format stores two digits per byte, while unpacked BCD uses one byte per digit with the upper 4 bits as 0xF.

13. Explain the concept of guard bits and sticky bits in floating-point arithmetic.

Guard bits and sticky bits are extra precision bits used during intermediate floating-point calculations to maintain accuracy before final rounding.

When an implementation computes a floating-point result, it may keep extra bits before rounding to the destination format. A typical explanation uses a guard bit, a round bit, and a sticky bit. The sticky bit is 1 if any discarded bit is 1. These bits help decide whether the stored result should round up or down.

The exact intermediate precision is implementation-dependent. For example, some older x86 code used the x87 80-bit extended format for intermediate results, while other code uses the declared format or different hardware instructions. Do not assume every binary64 calculation is first evaluated in 80 bits.

14. How do you convert a binary value to Gray code?

Gray code is formed by XORing a binary value with itself shifted right by one bit: G = B ^ (B >> 1). For the 3-bit binary value 100, the result is 110. Adjacent Gray-code values differ in one bit, which helps reduce ambiguous readings when a sensor changes state.

15. How can you inspect byte order?

First distinguish the host's native byte order from a file or protocol's specified byte order. Python reports native order with sys.byteorder. The struct format prefixes > and < serialize a 32-bit unsigned integer in big-endian and little-endian order, regardless of the host:

import struct
import sys

value = 0x12345678 print(sys.byteorder) print(struct.pack(“>I”, value).hex(” “)) # 12 34 56 78 print(struct.pack(”<I”, value).hex(” “)) # 78 56 34 12

Use the byte order required by the format when reading or writing data. A CPU's native order does not determine a file's order.

16. What happens when C converts between signed and unsigned 8-bit integers?

In C, converting a negative signed value to uint8_t is defined modulo 256. For example, (uint8_t)-56 is 200. If the implementation provides int8_t, converting an unsigned value such as 200 to int8_t is out of range; C does not require the result to be -56.

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

int main(void) { int8_t signed_value = -56; uint8_t bits = (uint8_t)signed_value;

printf("%d\n", signed_value);        // -56
printf("%u\n", (unsigned)bits);      // 200

}

Small integer types are promoted before arithmetic. On implementations that provide these 8-bit types, both int8_t and uint8_t values fit in int, so their arithmetic is performed as int; assigning the result to uint8_t then converts modulo 256.

17. How does exponent bias work in IEEE 754 binary32?

IEEE 754 binary32 stores an 8-bit exponent with a bias of 127. For normal values, subtract 127 from the stored exponent to get the actual exponent: a stored value of 127 means an exponent of 0. Exponent encodings 0 and 255 are reserved for subnormal values, zero, infinity, and NaN, so the normal exponent range is -126 to +127.

18. What is the difference between BCD, packed BCD, and zoned decimal formats?

BCD (Binary-Coded Decimal): Each decimal digit 0-9 is encoded in 4 bits (nibble). One byte holds two digits.

Packed BCD stores two decimal digits per byte. Five digits may be shown as 01 23 45, with a leading zero nibble. Some IBM packed-decimal formats reserve the final nibble for a sign, but the exact encoding depends on the format.

Zoned decimal stores each digit in a byte with zone bits in the upper nibble. In one common EBCDIC form, 123 is F1 F2 F3. Signed forms may encode the sign in the final digit's zone.

These formats trade storage size and compatibility differently. Check the format specification before interpreting a hex dump or exchanging decimal data.

19. What happens when a C signed integer is shifted left?

In C17, left-shifting a negative signed operand is undefined behavior. For a nonnegative signed operand, the mathematical result must fit the corresponding unsigned type; if it does, the result is converted back to the signed result type, which may be implementation-defined when it is out of range. Do not use signed left shifts to produce portable bit patterns.

For example, with C's optional exact-width types, shifting uint32_t value 0x40000000 left by one yields 0x80000000. The shift count must be less than the width of the promoted left operand.

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

int main(void) { uint32_t value = UINT32_C(0x40000000); uint32_t shifted = value << 1; printf(“%08” PRIX32 “\n”, shifted); // 80000000 }

20. How does the UTF-16 encoding work and why does it have surrogate pairs?

UTF-16 uses 16-bit code units, but Unicode has over 1 million possible characters—more than 65535. To represent characters beyond the Basic Multilingual Plane (BMP, U+0000 to U+FFFF), UTF-16 uses surrogate pairs.

The 2,048 code points from U+D800 to U+DFFF are reserved for surrogate code units and are not Unicode scalar values:

  • High surrogate: U+D800 to U+DBFF (1024 values)
  • Low surrogate: U+DC00 to U+DFFF (1024 values)

To encode U+10000 and above:

  1. Subtract 0x10000, giving a 20-bit value (0 to 0xFFFFF)
  2. Add 0xD800 to (value >> 10) for high surrogate (range: 0xD800-0xDBFF)
  3. Add 0xDC00 to (value & 0x3FF) for low surrogate (range: 0xDC00-0xDFFF)

Example: The emoji U+1F600 (Grinning Face) = 0x1F600. High surrogate = 0xD83D, Low surrogate = 0xDE00.

Java and JavaScript strings use UTF-16 code units. Windows APIs commonly use 16-bit wchar_t, though C does not require that width. In JavaScript, string indexing returns one code unit at a time, so a character outside the BMP occupies two indexes as a surrogate pair.

Further reading

Conclusion

A bit pattern only makes sense with its type, width, and format. Those details affect conversions, arithmetic, and serialized data.

When a value looks wrong, inspect the stored bits or bytes and check which rules produced them. Boolean logic and gates explains the hardware operations behind those patterns; instruction set architecture shows how processors use them.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science