AlgoViz

Number bases (binary & hex)

easy 14 min

Every number base works the same way: each digit is multiplied by the base raised to the power of its position.

Video lesson · Chapter 1 of 10

One byte, three readouts

0:00 / 10:59

Number bases (binary and hex)

1:27Reel

Read caption

Pip reads one rail of eight lanterns as binary, decimal and hexadecimal, then uses a bit mask to test one light. Each place doubles. Four bits make a hex digit.

How it works

Step through the idea, or press Play.

Step 1 of 3

Position sets the value. A digit is worth digit times base to the power of its position, counting from 0 on the right

Understand it

Start here

What a number base is

A number base (or radix) is how many different digits a number system uses before it has to carry into the next place. Decimal has ten digits, 0 to 9, because humans count on ten fingers. Binary has two, 0 and 1. Hexadecimal has sixteen, 0 to 9 and then A to F. The value of a number never changes; only the way it is written does. Forty-two is 42 in decimal, 101010 in binary and 2A in hex.

  • Binary, base 2

    Digits 0 and 1. Place values are powers of 2. The native language of hardware: every bit is a switch that is off or on.

  • Decimal, base 10

    Digits 0 to 9. Place values are powers of 10. What people type and read, so all user-facing numbers are decimal.

  • Hexadecimal, base 16

    Digits 0 to 9 and A to F. Place values are powers of 16. A compact way to write binary: one hex digit is four bits.

The one formula

Positional notation

All three systems are positional: a digit's position decides what it is worth. Number the positions from 0 on the right. A digit did_i in position ii is worth di×bid_i \times b^i, where bb is the base. Add those up and you have the value.

Value of a number in base b

N=∑i=0k−1di b i=dk−1b k−1+⋯+d1b 1+d0b 0,0≤di<bN = \sum_{i=0}^{k-1} d_i \, b^{\,i} = d_{k-1} b^{\,k-1} + \dots + d_1 b^{\,1} + d_0 b^{\,0}, \qquad 0 \le d_i < b
did_i is the digit in position ii, bb is the base and kk is the number of digits. Every digit must be smaller than the base, which is why binary has no digit 2 and hex needs letters for 10 to 15.

Reading any number

One procedure for every base. Only the multiplier changes.
BaseWrittenExpansionValue
10424×101+2×1004 \times 10^1 + 2 \times 10^040 + 2 = 42
21010101⋅25+0⋅24+1⋅23+0⋅22+1⋅21+0⋅201 \cdot 2^5 + 0 \cdot 2^4 + 1 \cdot 2^3 + 0 \cdot 2^2 + 1 \cdot 2^1 + 0 \cdot 2^032 + 8 + 2 = 42
162A2×161+10×1602 \times 16^1 + 10 \times 16^032 + 10 = 42
The number 42 in three bases. The rule is identical; the base is the only difference.

Base 10

Decimal, the base you already know

Decimal is the easiest place to see positional notation because you use it without thinking. The positions have names, ones, tens, hundreds, thousands, and each place is worth 10 times the place to its right.

Breaking down 1,234

1234=1×103+2×102+3×101+4×100=1000+200+30+41234 = 1 \times 10^3 + 2 \times 10^2 + 3 \times 10^1 + 4 \times 10^0 = 1000 + 200 + 30 + 4
Position 0 is worth 100=110^0 = 1, position 1 is worth 10, position 2 is worth 100, position 3 is worth 1000.

Why decimal still matters in CS

  • Input and output

    Every number a user types or reads is decimal, so programs convert at the edges.

  • The bridge

    Converting between binary and hex by hand, or checking a result, usually goes through a decimal sum.

  • Floating point

    0.1 has no exact binary form, so 0.1 + 0.2 is 0.30000000000000004. Decimal fractions and binary storage do not line up.

Base 2

Binary, the language of computers

At the hardware level a transistor is either off (0) or on (1). That is why every piece of data, text, images, video and code, is stored as binary. Each binary digit is a bit; the place values double as you move left: 1, 2, 4, 8, 16, 32, 64, 128.

  • Bit

    One binary digit, 0 or 1.

  • Nibble

    4 bits, values 0 to 15. Exactly one hex digit.

  • Byte

    8 bits, values 0 to 255 (28−12^8 - 1). Two hex digits, 00 to FF.

  • Word

    32 or 64 bits depending on the CPU. A 32-bit unsigned int tops out at 232−1≈4.292^{32} - 1 \approx 4.29 billion.

Powers of 2 to memorise

PowerValuePowerValue
202^01262^664
212^12272^7128
222^24282^8256
232^38292^9512
242^4162102^{10}1,024
252^5322162^{16}65,536
Double from 1, or halve back to 1. These appear in byte sizes, array limits, masks and complexity estimates.

How many bits does n need?

k bits hold 0…2k−1⇒bits(n)=⌊log⁡2n⌋+1 for n≥1k \text{ bits hold } 0 \dots 2^k - 1 \qquad\Rightarrow\qquad \text{bits}(n) = \lfloor \log_2 n \rfloor + 1 \text{ for } n \ge 1
42 needs ⌊log⁡242⌋+1=5+1=6\lfloor \log_2 42 \rfloor + 1 = 5 + 1 = 6 bits. Python gives it directly as (42).bit_length().

Converting

Decimal to binary, two ways

Way 1: subtract the largest power that fits

42: 128 no, 64 no, 32 yes (10 left), 16 no, 8 yes (2 left), 4 no, 2 yes (0 left), 1 no, giving 00101010. Good for mental maths.

Way 2: divide by 2 and keep the remainders

42 gives remainders 0, 1, 0, 1, 0, 1. Read upward: 101010. This is the method code uses, and it works for any base: divide by b instead of 2.
Python
def by_place_values(n, width=8):    bits = ""    for p in range(width - 1, -1, -1):        if 2 ** p <= n:            bits += "1"            n -= 2 ** p        else:            bits += "0"    return bitsdef by_division(n):    if n == 0:        return "0"    bits = ""    while n > 0:        bits = str(n % 2) + bits   # prepend: first remainder is the lowest bit        n //= 2    return bitsprint(by_place_values(42))   # 00101010print(by_division(42))       # 101010print(bin(42), f"{42:08b}")  # 0b101010 00101010
Both methods by hand, checked against Python's built-ins.
Edit and run it in your browser

Back again

Binary to decimal

Going back is just the positional formula: add up the place values of the bits that are on. For 101010 that is 32+8+2=4232 + 8 + 2 = 42. Code usually uses a neater form called Horner's method: scan left to right, and for each digit multiply the running total by the base and add the digit.

Horner's method

1010102=((((1⋅2+0)⋅2+1)⋅2+0)⋅2+1)⋅2+0=42101010_2 = ((((1 \cdot 2 + 0) \cdot 2 + 1) \cdot 2 + 0) \cdot 2 + 1) \cdot 2 + 0 = 42
Running total: 1, 2, 5, 10, 21, 42. No powers needed, one multiply and one add per digit, and it works for any base.
Python
DIGITS = "0123456789ABCDEF"def from_base(s, base):    total = 0    for ch in s.upper():        total = total * base + DIGITS.index(ch)    return totalprint(from_base("101010", 2))   # 42print(from_base("2A", 16))      # 42print(int("101010", 2), int("2A", 16), int("0x2A", 0))   # 42 42 42
Horner's method from scratch, then the built-in that does the same.
Edit and run it in your browser

Base 16

Hexadecimal, the programmer's shorthand

Binary is long: 255 is 11111111. Hex shortens it without losing the link to the bits. Hex needs sixteen digits, so after 9 it borrows letters: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Place values are powers of 16: 1, 16, 256, 4096.

Why one hex digit is four bits

16=24⇒16i=24i16 = 2^4 \quad\Rightarrow\quad 16^i = 2^{4i}
Each hex place lines up exactly with a block of four binary places. A hex digit and a nibble hold the same 16 values, 0 to 15, so they map one to one.

The sixteen nibbles

HexDecBinaryHexDecBinary
000000881000
110001991001
220010A101010
330011B111011
440100C121100
550101D131101
660110E141110
770111F151111
Hex to decimal to binary. Learn the A to F row by the trick below and the rest follows from counting.

Hex and binary

Swap digits for nibbles

Converting between hex and binary

No arithmetic and no decimal in between. That direct mapping is the whole reason hex exists.

Two worked examples

0x2A=0010⏟2  1010⏟A=42110101102=1101⏟D  0110⏟6=0xD6=214\text{0x2A} = \underbrace{0010}_{2}\;\underbrace{1010}_{\text{A}} = 42 \qquad 11010110_2 = \underbrace{1101}_{\text{D}}\;\underbrace{0110}_{6} = \text{0xD6} = 214
Check the second: 13×16+6=21413 \times 16 + 6 = 214, and 128+64+16+4+2=214128 + 64 + 16 + 4 + 2 = 214.
Python
HEX = "0123456789ABCDEF"def to_hex(n):    if n == 0:        return "0"    out = ""    while n > 0:        out = HEX[n % 16] + out   # 42 % 16 = 10 -> "A", then 2 -> "2"        n //= 16    return outdef hex_to_bin(h):    return " ".join(format(int(c, 16), "04b") for c in h)def bin_to_hex(b):    b = b.zfill((len(b) + 3) // 4 * 4)   # pad on the left to a multiple of 4    return "".join(HEX[int(b[i:i + 4], 2)] for i in range(0, len(b), 4))print(to_hex(42), to_hex(255))   # 2A FFprint(hex_to_bin("2A"))          # 0010 1010print(bin_to_hex("11010110"))    # D6print(f"{42:X} {42:#x} {255:02X}")   # 2A 0x2a FF
Decimal to hex by dividing by 16, and the nibble swap in both directions.
Edit and run it in your browser

Must-know conversions

DecimalBinaryHexWhy it matters
000000Zero
100011The lowest bit
810008232^3
101010AThe first hex letter
151111FLargest single hex digit, a full nibble
161000010242^4, the first two-digit hex number
421010102AOur worked example
127011111117FLargest signed 8-bit value
1281000000080Only the top bit of a byte
25511111111FFLargest byte value
256100000000100282^8, needs a ninth bit

Any base

Converting between any two bases

Pick the route

Octal, base 8, works like hex with groups of three bits: chmod 755 is 111 101 101.

The division method in general

N=q⋅b+r,0≤r<b⇒d0=N mod b,then repeat on q=⌊N/b⌋N = q \cdot b + r, \quad 0 \le r < b \qquad\Rightarrow\qquad d_0 = N \bmod b, \quad \text{then repeat on } q = \lfloor N / b \rfloor
Each step peels off the lowest digit. It takes as many steps as there are digits: ⌊log⁡bN⌋+1\lfloor \log_b N \rfloor + 1, so conversion is O(log⁡N)O(\log N).

Do

  • Use int(s, base) to parse and format(n, "b"), "x" or "X" to print.
  • Pad with format(n, "08b") when the width matters.
  • Go hex to binary digit by digit, four bits each.
  • Special-case 0 in hand-written converters.

Avoid

  • Forgetting that bin() and hex() add 0b and 0x.
  • Calling int("2A") without a base: ValueError.
  • Reading division remainders top-down.
  • Detouring through decimal to convert hex to binary.

Where you will see it

Bases in real systems

  • Memory addresses

    Debuggers and stack traces print addresses in hex, such as 0x7FFF5FBFF8C0, because each digit maps to four address bits.

  • Colours

    #FF5733 is three bytes: red FF = 255, green 57 = 87, blue 33 = 51.

  • Unix permissions

    chmod 755 is octal: 7 = 111 (rwx) for the owner, 5 = 101 (r-x) for group and others.

  • Networking

    Each IPv4 octet, as in 192.168.1.1, is 8 bits (0 to 255). MAC addresses like 00:1A:2B:3C:4D:5E are six hex bytes.

  • Bit flags

    READ = 1, WRITE = 2, EXEC = 4 each own one bit, so READ | WRITE = 3 holds both.

  • Interview problems

    Number of 1 bits, reverse bits, single number with XOR and power of two all start from reading a number as bits.

Binary patterns to recognise

PatternFormulaExamples
All ones2n−12^n - 11111 = 15, 11111111 = 255
A single 1 then zeros2n2^n1000 = 8, 10000000 = 128
Alternating 1 and 0repeat 101010 = 10, 101010 = 42, 10101010 = 170
Power of two testn & (n - 1) == 08 & 7 = 1000 & 0111 = 0
All ones is one less than the next power of two: 11112+1=1000021111_2 + 1 = 10000_2.
Where the bases meet
  1. 1You type 42decimal at the keyboard
  2. 2Stored as 00101010binary in memory
  3. 3Debugger shows 0x2Ahex for humans reading bits

One value, three views: people, hardware, and programmers in between.

Recap

Key takeaways

Key points

  • Positional notation is universal: N=∑dibiN = \sum d_i b^i, with every digit smaller than the base.
  • Binary is base 2 because hardware has two states. Place values are 1, 2, 4, 8 ... and nn needs ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 bits.
  • Decimal to any base: take n % b, then n //= b, and reverse the remainders. Any base to decimal: Horner, total = total * b + d.
  • Hex is compact binary: 16=2416 = 2^4, so one hex digit is one nibble and two hex digits are one byte.
  • Hex letters: A = 10 up to F = 15 (letter position plus 9). 0xFF = 255 is the largest byte.
  • Memorise powers of 2 up to 210=10242^{10} = 1024 and the anchors 42 = 101010 = 0x2A.
  • In Python: int(s, base), bin, hex, format(n, "08b") and n.bit_length().

Sources