Number bases (binary & hex)
easy 14 minEvery number base works the same way: each digit is multiplied by the base raised to the power of its position.
See it run
Take 42 apart in decimal, build it bit by bit as 00101010, rebuild it by dividing by 2, then write it as 0x2A and see each hex digit become four bits.
Operations
Decimal place values
Decimal is positional: each digit is multiplied by a power of 10 that depends on where it sits. $42 = 4 \times 10^1 + 2 \times 10^0$. Every other base works the same way with a different multiplier.
Step 1 of 5
42 has two digits
| 10¹ | 10⁰ | |
|---|---|---|
| digit | 4 | 2 |
| place | 10 | 1 |
| digit × place | ? | ? |
The number 42 is written with the digits 4 and 2. On their own they are just symbols. Their position decides what they are worth: the rightmost place is worth 10^0 = 1, the next 10^1 = 10.
Step 1: 42 has two digits
def place_values(n, base=10): digits = [int(d) for d in str(n)] k = len(digits) total = 0 for i, d in enumerate(digits): power = k - 1 - i part = d * base ** power print(f"{d} x {base}^{power} = {part}") total += part return totalprint(place_values(42)) # 4 x 10^1 = 40, 2 x 10^0 = 2, then 42print(place_values(1234)) # 1000 + 200 + 30 + 4 = 1234- Time
- O(d)
- Space
- O(d)
- d
- number of digits
- same rule in base b
- digit × b^position
Read any number right to left: position 0, 1, 2... and multiply each digit by base to that power. Master it in decimal once and binary and hex are the same idea.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading division remainders top-down
criticalThe first remainder is the lowest bit. Joining them in the order they appear writes the number backwards: 42 comes out as 010101, which is 21.
Wrongbits = ""while n > 0: bits += str(n % 2) # appends the lowest bit last n //= 2return bits # 42 -> "010101"Rightbits = ""while n > 0: bits = str(n % 2) + bits # prepend n //= 2return bits or "0" # 42 -> "101010"Forgetting the 0b and 0x prefixes
majorbin() and hex() return strings that start with '0b' or '0x'. Counting characters or comparing them as digits without stripping the prefix gives wrong answers.
Wronglen(bin(42)) # 8, counts the "0b"hex(42) == "2A" # FalseRightlen(bin(42)[2:]) # 6format(42, "X") == "2A" # True, no prefix, upper caseParsing a base-16 string without saying so
majorint() assumes base 10 unless told otherwise, so hex digits like A raise ValueError and a string like '10' silently means ten instead of sixteen.
Wrongint("2A") # ValueErrorint("10") # 10, but you meant 0x10Rightint("2A", 16) # 42int("0x10", 0) # 16, base 0 reads the prefixLosing leading zeros
minorbin(5) is '0b101', not 8 bits. Byte dumps, nibble mapping and bit-by-bit comparisons need a fixed width.
Wrongbin(5)[2:] # '101'Rightformat(5, "08b") # '00000101'f"{5:08b}" # sameReturning an empty string for zero
majorA while n > 0 loop never runs for 0, so a hand-written converter returns '' instead of '0'.
Wrongdef to_base(n, b): out = "" while n > 0: out = DIGITS[n % b] + out n //= b return out # to_base(0, 2) -> ""Rightdef to_base(n, b): if n == 0: return "0" out = "" while n > 0: out = DIGITS[n % b] + out n //= b return outExpecting bin() to show two's complement
minorPython ints have no fixed width, so bin(-5) is '-0b101' with a minus sign. To see the 8-bit two's complement pattern, mask the value first.
Wrongbin(-5) # '-0b101'Rightformat(-5 & 0xFF, "08b") # '11111011'
Interview tips
Spot it fast
- A 0x prefix, # colour code or memory address means hex.
- Flags, masks, permissions and "number of 1 bits" mean binary.
- Each hex digit is exactly 4 bits; two hex digits are one byte.
Numbers to know cold
- Powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.
- A = 10 through F = 15; 0xF = 1111 = 15.
- 0xFF = 255, 0x100 = 256, 0x7F = 127, 0x80 = 128.
- 42 = 101010 = 0x2A.
Say it in the interview
- "Value is the sum of digit times base to the power of its position."
- "To convert from decimal, take n mod b for the last digit and divide by b, then reverse."
- "n needs floor(log2 n) + 1 bits, so conversion is O(log n)."
Traps
- Remainders come out lowest digit first: reverse them.
- bin() and hex() add prefixes and drop leading zeros.
- int(s) is base 10 unless you pass the base.