Skip to main content

Section A.3 Hexadecimal and Binary Numbers

Register values are almost always written in binary or hexadecimal rather than decimal, because each binary digit of a register is a separate setting and these two bases show those digits. In C a binary number is written with the prefix 0b and a hexadecimal one with 0x, the same prefixes Python uses. (0b is an extension that the compiler we use accepts; 0x is standard C.)
Binary. Each digit of a binary number is a bit, and the bits are counted from 0, starting at the right. Bit \(n\) is worth \(2^n\text{.}\) So 0b00100000 has only bit 5 set, and its value is \(2^5 = 32\text{.}\) When we say a register bit is “bit 5”, this is the counting we mean. In the comments in the first chapter’s code, 0b...0001 stands for a 32-bit value whose leading bits are all 0.
Hexadecimal. Hexadecimal is base 16, with the digits 0 to 9 followed by A to F for the values 10 to 15. Its usefulness is that one hexadecimal digit stands for exactly four bits, so converting between hexadecimal and binary is done one digit at a time, using Table A.3.1.
Table A.3.1. Each hexadecimal digit is four bits
Hex Binary Decimal Hex Binary Decimal
0 0000 0 8 1000 8
1 0001 1 9 1001 9
2 0010 2 A 1010 10
3 0011 3 B 1011 11
4 0100 4 C 1100 12
5 0101 5 D 1101 13
6 0110 6 E 1110 14
7 0111 7 F 1111 15
For example, 0x20 is the digit 2 followed by the digit 0, which is 0010 followed by 0000, so 0x20 is 0b0010 0000: only bit 5 set, the same number as above. In the other direction, split a binary number into groups of four bits starting from the right, and replace each group by its digit: 0b1110 1011 is 0xEB. A 32-bit register value is exactly eight hexadecimal digits.
In this book we write long hexadecimal values with a space in the middle, such as 0x5000 0014, to make them easier to read. In code the digits have to be written together, 0x50000014: C allows neither spaces nor Python’s underscores inside a number.

Check Your Understanding Check Your Understanding

1.

Which binary number is 0xA3?
  • 0b1010 0011
  • Correct. A is 1010 and 3 is 0011, in the same order as the digits.
  • 0b0011 1010
  • These are the right two groups in the wrong order. The left hexadecimal digit becomes the left four bits.
  • 0b1010 0000 0011
  • Each hexadecimal digit is exactly four bits, so two digits make eight bits, with nothing in between.
  • 0b1100 0011
  • 1100 is C, which is 12. A is 10, which is 1010.