Data Representation (COA Core #2)
The CPU sees only bits. Whether 11111111 means 255, -1, or part of a float is
decided by the type the compiler gives it. This post is the translation table:
bases, two’s complement, IEEE 754, and the byte order of multi-byte values.
Binary, decimal, and hexadecimal
Positional notation: the value of a digit depends on its position.
\[ 1011_2 = 1\cdot2^3 + 0\cdot2^2 + 1\cdot2^1 + 1\cdot2^0 = 11_{10} \]
Hex is base 16, and one hex digit is exactly four bits, which is why it is used for memory dumps and bit patterns.
| Hex | Binary | Decimal |
|---|---|---|
0x0 |
0000 | 0 |
0xA |
1010 | 10 |
0xF |
1111 | 15 |
0xFF |
1111 1111 | 255 |
0x10 |
0001 0000 | 16 |
0b1011; // 11 (C++14 binary literal)
0xB; // 11
0o13; // 11
To convert binary to hex, group bits in fours from the right: 10110110 →
1011 0110 → 0xB6. To convert to decimal, add the powers of two that are set.
ASolution
Eight, because each digit is four bits and \(32/4 = 8\). A 64-bit value needs 16.
Signed and unsigned integers
An unsigned \(n\)-bit integer represents \(0\) to \(2^n - 1\). All bit patterns are values, and arithmetic wraps modulo \(2^n\).
A signed integer uses the top bit as a sign and has range \(-2^{n-1}\) to \(2^{n-1}-1\). Three historical encodings:
| Encoding | 8-bit example for -5 | Range |
|---|---|---|
| Sign-magnitude | 1000 0101 |
\(-127\) to \(127\) |
| One’s complement | 1111 1010 |
\(-127\) to \(127\) |
| Two’s complement | 1111 1011 |
\(-128\) to \(127\) |
Two’s complement won because addition and subtraction need no special cases: the same adder works for signed and unsigned, and there is only one zero.
ASolution
Zero uses the pattern 0000 0000, which would otherwise be the positive
counterpart of the negative minimum. With 8 bits, 1000 0000 has no positive
match, giving \(-128\) but only \(+127\).
Two’s complement
To negate a value: invert all bits and add one.
\[ -x = \sim x + 1 \]
Example with 8 bits: \(x = 5 = 0000\,0101\); \(\sim x = 1111\,1010\); add 1 → \(1111\,1011 = -5\).
The top bit has weight \(-2^{n-1}\), the rest are positive:
\[ 1111\,1011_2 = -128 + 64 + 32 + 16 + 8 + 2 + 1 = -5 \]
Sign extension: when widening a signed value, copy the sign bit into the new high
bits. int8_t(-5) → int32_t is 11111111 11111111 11111111 11111011, not zero
extended.
int8_t a = -5; // 0xFB
int32_t b = a; // 0xFFFFFFFB, sign-extended
uint32_t c = a; // also 0xFFFFFFFB: conversion, then reinterpreted unsigned
0xB6?ASolution
\(0xB6 = 182\), and since the top bit is set, subtract 256: \(182 - 256 = -74\).
Integer overflow
Unsigned arithmetic wraps modulo \(2^n\), which is defined behaviour. Signed overflow is undefined in C and C++; the hardware sets the overflow flag, but the language does not promise what happens.
uint8_t u = 255;
uint8_t v = u + 1; // 0: the int 256 is converted back to uint8_t
int8_t s = 127;
int t = s + 1; // 128: promotion to int, no overflow yet
int8_t w = s + 1; // implementation-defined conversion, usually -128
int x = 2000000000;
x + x; // UB: signed overflow exceeds INT_MAX
Overflow detection in hardware:
- Unsigned: carry out of the most significant bit.
- Signed: the carry into and out of the sign bit differ. Equivalently, two operands with the same sign produce a result with a different sign.
int a, b, sum;
bool overflow = __builtin_add_overflow(a, b, &sum); // GCC/Clang
int8_t(127) + int8_t(1) computed as an int, not an 8-bitoverflow?
ASolution
Integer promotion: 8- and 16-bit types promote to int before arithmetic. The
result is 128, which fits in int; the overflow only happens if you store it
back into an int8_t.
Floating-point representation
A floating-point number is stored as sign, exponent, and significand (mantissa):
\[ (-1)^s \times 1.f \times 2^{e - \text{bias}} \]
The leading 1 is implicit for normalized numbers, which buys one extra bit of precision.
IEEE 754 single precision (32-bit):
| Field | Bits | Meaning |
|---|---|---|
| sign | 1 | 0 positive, 1 negative |
| exponent | 8 | biased by 127 |
| fraction | 23 | bits after the implicit 1 |
Double precision: 1 sign, 11 exponent (bias 1023), 52 fraction bits.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum height=0.55cm, font=\scriptsize\ttfamily}]
\node[c, fill=blue!12, minimum width=0.9cm] (s) at (0,0) {s};
\node[c, fill=orange!18, minimum width=2.6cm] (e) at (1.75,0) {exponent (8)};
\node[c, fill=green!15, minimum width=5.0cm] (f) at (5.55,0) {fraction (23)};
\node[font=\scriptsize, anchor=north] at (0,-0.45) {1 bit};
\node[font=\scriptsize, anchor=north] at (1.75,-0.45) {bias 127};
\node[font=\scriptsize, anchor=north] at (5.55,-0.45) {implicit leading 1};
\node[font=\scriptsize, anchor=north] at (2.7,-1.0) {32 bits total, little-endian byte order in memory};
\end{tikzpicture}
Worked example, 5.5:
- \(5.5 = 101.1_2 = 1.011_2 \times 2^2\).
- Exponent field: \(2 + 127 = 129 = 1000\,0001_2\).
- Fraction: \(011000\ldots\).
- Bits:
0 10000001 01100000000000000000000=0x40B00000.
#include <cstdint>
#include <cstdio>
#include <cstring>
float f = 5.5f;
std::uint32_t bits;
std::memcpy(&bits, &f, 4); // C++20: std::bit_cast
std::printf("%08X\n", bits); // 40B00000
-1.0f?ASolution
Sign 1, exponent 127 (0111 1111), fraction all zeros. The encoding is
0xBF800000.
IEEE 754 details
Special values:
| Exponent | Fraction | Meaning |
|---|---|---|
| all zeros | all zeros | ±0 |
| all zeros | nonzero | subnormal (no implicit 1) |
| all ones | all zeros | ±infinity |
| all ones | nonzero | NaN |
Subnormals fill the gap between zero and the smallest normal number (\(2^{-126} \approx 1.18 \times 10^{-38}\) for float); the smallest positive float is about \(1.4 \times 10^{-45}\).
The exponent bias lets the stored exponent be unsigned. For float, stored 127 means \(2^0\); for double, 1023.
ASolution
Arithmetic needs results for overflow and invalid operations (1⁄0, 0/0). They cannot be represented as finite values, so the all-ones exponent is reserved.
Precision and rounding
A float has 24 significant bits (23 stored plus the implicit 1), which is about 7 decimal digits. A double has 53 bits, about 16 digits.
Machine epsilon is the gap between 1 and the next representable value:
\[ \varepsilon_{\text{float}} = 2^{-23} \approx 1.19 \times 10^{-7}, \qquad \varepsilon_{\text{double}} = 2^{-52} \approx 2.22 \times 10^{-16} \]
The unit in the last place (ULP) scales with the exponent, so the spacing near \(10^6\) is much larger than near 1.
Rounding is round-to-nearest, ties-to-even by default. That is why:
0.1 + 0.2 == 0.3; // false
0.1 + 0.2; // 0.30000000000000004
0.1 and 0.2 have no finite binary expansion (like 1⁄3 in decimal), so they are rounded before the addition. The sum is the correctly rounded result of those rounded inputs, not the exact decimal sum.
#include <cmath>
std::fabs((0.1 + 0.2) - 0.3) < 1e-9; // compare with a tolerance
Catastrophic cancellation: subtracting two nearly equal numbers loses significant digits. \(1.0000001 - 1.0\) leaves only the low bits, which may be mostly rounding error. Rearranging the formula often fixes it.
0.1f + 0.2f == 0.3f false in float too?ASolution
The three literals are rounded to different float values. The rounded sum of the first two is not equal to the rounded value of 0.3; the error is just larger than in double.
Endianness
Multi-byte values are stored in memory either least-significant byte first (little-endian) or most-significant byte first (big-endian).
uint32_t x = 0x01020304 in memory:
| Address | Little-endian | Big-endian |
|---|---|---|
| 0 | 04 |
01 |
| 1 | 03 |
02 |
| 2 | 02 |
03 |
| 3 | 01 |
04 |
x86-64 and ARM (in default mode) are little-endian. Network byte order is
big-endian, which is why htonl/ntohl exist. ARM can switch endianness, and some
formats (UTF-16, TIFF) can specify it per file.
std::uint32_t x = 0x01020304;
unsigned char bytes[4];
std::memcpy(bytes, &x, 4); // bytes[0] is 0x04 on little-endian
Endianness does not affect arithmetic, only the byte layout in memory, files, and network protocols.
ASolution
No. printf("%u", x) prints 16909060 on both. The CPU loads the bytes according
to its endianness, and the value is the same; only the memory order differs.
Character encoding
- ASCII: 7-bit, code points 0–127.
'A'= 65,'a'= 97,'0'= 48. - Latin-1: 8-bit, 256 code points; not Unicode.
- UTF-8: variable 1–4 bytes, backward compatible with ASCII.
- UTF-16: 2 or 4 bytes (surrogate pairs), used internally by Java, Windows.
UTF-8 byte patterns:
| Code point range | Bytes | Pattern |
|---|---|---|
| U+0000–U+007F | 1 | 0xxxxxxx |
| U+0080–U+07FF | 2 | 110xxxxx 10xxxxxx |
| U+0800–U+FFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
| U+10000–U+10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Examples: 'é' (U+00E9) is C3 A9; '€' (U+20AC) is E2 82 AC; an emoji
(U+1F600) is F0 9F 98 80.
std::string holds bytes, not characters. s.size() counts bytes; iterating with
for (char c : s) iterates bytes. Use UTF-8-aware libraries or std::u32string
for code points.
ASolution
It is ASCII-compatible for the common characters, self-synchronizing (a byte
starting with 10 is a continuation), and compact for Latin text. No byte order
is needed, unlike UTF-16.
Bugs and edge cases
- Assuming
charis signed. It is implementation-defined; usesigned charorunsigned charwhen the distinction matters. - Signed overflow in C++. Use unsigned types or checked arithmetic; do not rely on wrap.
- Comparing floats with
==. Use a tolerance or compare integers if the values are exact. - Assuming decimal literals are exact.
0.1is already rounded. - Mixing float and double. The float is promoted, but its lost precision is not recovered.
- Endianness in binary files. Specify it in the format or use a portable serialization library.
- Byte-based string indexing. UTF-8 indexing can split a character.
- NaN comparisons. All comparisons with NaN are false, including
NaN == NaN.
x == x false for a NaN?ASolution
IEEE 754 defines NaN as unordered: it is not equal to anything, including
itself. Use std::isnan to test for it.
Next: CPU Pipelining (COA Core #3) — hazards, forwarding, and the cost of a mispredicted branch.