Binary and Number Systems

Bits, bytes, binary and hexadecimal, converting between bases, and why integers overflow.

What is it?

Inside a computer, everything (numbers, text, images, your code) is stored as bits. A bit is a single 0 or 1.

- A byte is 8 bits, so it can hold 2⁸ = 256 different patterns. - Binary (base 2) writes numbers using only 0 and 1. - Decimal (base 10) is the everyday system with digits 0–9. - Hexadecimal (base 16) uses 0–9 and A–F (A=10 … F=15). One hex digit is exactly 4 bits, so two hex digits describe one byte. That makes hex a compact, human-friendly way to write binary: 0xFF = 11111111 = 255.

In every base, a digit's value depends on its position. In decimal, 347 means 3×100 + 4×10 + 7×1. In binary, 1011 means 1×8 + 0×4 + 1×2 + 1×1 = 11.

Why binary? Electronic circuits are most reliable when they only need to tell two states apart (voltage high or low, switch on or off). Two states are easy to build, fast to switch and resistant to noise.

Integer sizes. Many languages store integers in a fixed number of bits: 8, 16, 32 or 64. An unsigned 8-bit integer holds 0–255. A signed 8-bit integer holds −128 to 127. When a result doesn't fit, you get overflow.

Explain like I'm 10

Binary is like a row of light switches where each switch is worth double the one to its right: 1, 2, 4, 8, 16… To show a number, you flip on the switches that add up to it. Overflow is a car's odometer rolling from 999999 back to 000000.

Examples

Converting between bases

n = 202

print(bin(n))   # '0b11001010'
print(hex(n))   # '0xca'
print(oct(n))   # '0o312'

# And back again: int(text, base)
print(int("11001010", 2))  # 202
print(int("ca", 16))       # 202

# Literals in code
print(0b1010, 0xFF)  # 10 255

Python has built-ins for each direction. The 0b, 0x and 0o prefixes mark binary, hex and octal literals.

Converting by hand (decimal → binary)

function toBinary(n) {
  if (n === 0) return "0";
  let bits = "";
  while (n > 0) {
    bits = (n % 2) + bits; // remainder is the next bit (from the right)
    n = Math.floor(n / 2);
  }
  return bits;
}

console.log(toBinary(13));          // "1101"
console.log((13).toString(2));      // "1101"  (built-in)
console.log(parseInt("1101", 2));   // 13

Repeatedly divide by 2 and collect the remainders; read them in reverse. JavaScript's toString(base) and parseInt(text, base) do the same thing.

Overflow in C

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

int main(void) {
    uint8_t small = 255;
    small = small + 1;          // wraps around
    printf("%u\n", small);     // 0

    int32_t big = 2147483647;   // largest 32-bit signed int
    // big + 1 here would be undefined behavior in C for signed types!
    printf("%d\n", big);
    return 0;
}

Unsigned integers in C wrap around (255 + 1 → 0 for 8 bits). Signed overflow is undefined behavior: the compiler may assume it never happens, so never rely on it.

How it works

Place values. In base b, each position is worth b times the position to its right:

  • Decimal: …, 1000, 100, 10, 1
  • Binary: …, 16, 8, 4, 2, 1
  • Hex: …, 4096, 256, 16, 1

Binary → decimal: add up the place values where the bit is 1. Decimal → binary: divide by 2 repeatedly; the remainders, read bottom-up, are the bits. Binary ↔ hex: group bits in fours from the right; each group is one hex digit (1111 = F, 1010 = A).

Negative numbers are almost always stored with two's complement: to negate, flip every bit and add 1. In 8 bits, −1 is 11111111. The top bit acts as the sign, and the same adder circuit works for both signed and unsigned values.

n bits give 2ⁿ patterns: unsigned range 0 to 2ⁿ−1, signed range −2ⁿ⁻¹ to 2ⁿ⁻¹−1.

Language differences: Python ints grow as needed and never overflow. JavaScript number is a 64-bit float, exact for integers only up to Number.MAX_SAFE_INTEGER (2⁵³−1); beyond that, use BigInt. C, Java, Go and Rust use fixed-size integers.

Decimal 202 in one byte (8 bits):

  place value:  128  64  32  16   8   4   2   1
  bit:            1   1   0   0   1   0   1   0     = 128+64+8+2 = 202
                 └─── C (12) ───┘ └─── A (10) ──┘     = 0xCA

  8-bit unsigned:  0 ……………………………… 255   then 255 + 1 → 0   (wraps)
  8-bit signed:  −128 ………… 0 ………… 127   (two's complement)

Why does it exist?

Binary exists because hardware is built from two-state switches. Hex exists because long binary strings are hard for humans to read, and hex maps onto bits perfectly (4 bits per digit). Fixed-size integers exist because the CPU has fixed-width registers and arithmetic circuits; fixed sizes make math fast and memory layout predictable.

When to use it

You'll meet these ideas when:

- Reading colors (#FF8800), memory addresses, hashes or byte dumps in hex. - Working with file formats, network protocols or hardware registers. - Choosing an integer type in C, Java, Go or Rust (or a database column). - Debugging strange values: a negative number that should be huge, or a counter that suddenly resets to 0. - Using flags and masks with bitwise operations.

When not to use it

You rarely need to convert bases by hand in day-to-day code; use the language's built-ins. And don't pick tiny integer types to "save memory" without a reason: the overflow risk usually outweighs a few bytes saved. For money, use integers of the smallest unit (cents) or a decimal type, not floats.

Common mistakes

  • Confusing bits and bytes. Network speeds are usually in bits per second (Mbps); file sizes in bytes (MB). 100 Mbps ≈ 12.5 MB/s.

  • Assuming integers never overflow. In C, Java or a 32-bit database column, a counter can silently wrap or exceed its limit.

  • Trusting large integers in JavaScript. Above 2⁵³−1, number can't represent every integer exactly; IDs from APIs can be silently corrupted. Use BigInt or keep them as strings.

  • Reading a hex string like "10" as ten. 0x10 is 16.

  • Relying on signed integer overflow in C to wrap. It's undefined behavior; use unsigned types or check before adding.

Practice exercises

  1. Easy:

    By hand, convert 45 to binary and hex, then convert 0x3F and 0b10011 to decimal. Check your answers with Python's bin, hex and int.

  2. Medium:

    Write a function toBase(n, base) (bases 2–16) without using built-in conversion, and a matching fromBase(text, base). Test them against the built-ins.

  3. Hard:

    Write a function that, given a bit width (like 8 or 16), returns the signed and unsigned ranges, and another that converts a negative integer into its two's complement bit string for that width.

Interview questions

How many values can n bits represent?

2ⁿ. One byte (8 bits) gives 256 values: 0–255 unsigned or −128 to 127 signed.

Why do computers use binary?

Digital circuits reliably distinguish two states (high/low voltage). Two-state components are simple, fast, cheap and tolerant of electrical noise, and Boolean logic maps directly onto them.

Why is hexadecimal popular with programmers?

Each hex digit is exactly 4 bits, so a byte is always two hex digits. It's far more compact than binary while still mapping cleanly onto the underlying bits.

Convert 0b1101 and 0x2A to decimal.

0b1101 = 8 + 4 + 1 = 13. 0x2A = 2×16 + 10 = 42.

What is two's complement?

The standard way to represent signed integers: a negative number is formed by inverting all bits of its positive value and adding 1. It gives one representation of zero and lets the same adder handle signed and unsigned addition.

What is integer overflow?

When an arithmetic result is too large (or small) for the integer type storing it. Depending on the language it wraps around, throws, saturates, or (for signed integers in C/C++) is undefined behavior.

Does Python have integer overflow?

Not for its built-in int, which has arbitrary precision and grows to fit any value (limited only by memory). Fixed-size types in libraries like NumPy can still overflow.

What is `Number.MAX_SAFE_INTEGER` in JavaScript, and why does it exist?

2⁵³ − 1 (9007199254740991). JavaScript numbers are 64-bit floats with 53 bits of precision, so integers above this can't all be represented exactly. BigInt handles larger integers.

What's the maximum value of a signed 32-bit integer?

2³¹ − 1 = 2,147,483,647. The minimum is −2³¹ = −2,147,483,648.

Scenario: a database ID column suddenly rejects inserts after years of use. What's a likely cause?

The ID column is a 32-bit integer and the sequence passed 2,147,483,647. The fix is migrating the column to a 64-bit type (BIGINT).