Skip to main content

Section 5.4 Hexadecimal Numbers

And finally, a brief excursion into hexadecimal numbers:

Aside: Video Description.

Binary is the native number system of the computer, but it is often convenient for us to talk in the hexadecimal number system (HEX), that is, in base-16.
HEX digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F (0-15)
Example: 0xAC means "A" * \(16^1\) + "C" * \(16^0\) = 10 * 16 + 12 * 1 = 172 in decimal
The "0x" indicates that what follows is in hex
Another example: 0x57 means 5 * \(16^1\) + 7 * \(16^0\) = 87 in decimal

Subsection 5.4.1 Why Use Hexadecimal?

Binary numbers can be REALLY long (used in memory location addressing for example.)
  • Need: easy shorthand for binary
  • Solution: HEX
    • Condense 4 bits (binary digits) into 1 hexadecimal digit
    • Example: 1011 binary = 11 decimal = B hexadecimal
  • 2-byte words (16 bits) can then be written as four HEX digits
We want powers of 2 (binary) for easy conversion.
Alternative?

Subsection 5.4.2 Decimal to Hexadecimal

We already know how this works: keep dividing by 16, record the remainders in reverse order!
23,597    /16       = 1,474  R13 (D)     * 16^0   LSD
 1,474    /16       = 92     R2          * 16^1    |
    92    /16       = 5      R12 (C)     * 16^2    V
     5    /16       = 0      R5          * 16^3   MSD

23,597              ->       0x5C2D

Subsection 5.4.3 Binary to Hexadecimal and Decimal

We can go directly from binary to decimal, or via hex.
Example: 16-bit binary integer
0101   1100   0010   1101    = 23,597    Decimal
  5    C (12)   2    D (13)  = 0x5C2D    HEX
16^3   16^2   16^1   16^0                (HEX place values)
\(5 \times 16^3 + 12 \times 16^2 + 2 \times 16^1 + 13 \times 16^0\)
\(= 5 \times 4096 + 12 \times 256 + 2 \times 16 + 13 \times 1\)
\(= 20,480 + 3072 + 32 + 13\)
\(= 23,597\) Decimal
Remember: precede hexadecimal number with 0x in order to avoid confusion with decimal number 0x5C2D
Hexadecimal to decimal: best done via binary!
0x15A9 2-byte hexadecimal (base-16) number
Hex-to-binary: each hex digit is 4 binary digits
                1    5    10   9
0x15A9        0001 0101 1010 1001
MSB is 0, so decimal value is the same for unsigned, signed-magnitude, and 2’s complement representations
Binary-to-decimal:
=5545

Subsection 5.4.4 Another Example

0xB5A9 2-byte hexadecimal (base-16) number
Hex-to-binary:
            11    5   10    9
0xB5A9     1011 0101 1010 1001
Now MSB is 1, so decimal value depends on which representation we use...
Binary-to-decimal:
Unsigned: \(2^{15} + 2^{13} + 2^{12} + 2^{10} + 2^8 + 2^7 + 2^5 + 2^3 + 2^0 = 46,505\)
Signed magnitude: \(-(2^{13} + 2^{12} + 2^{10} + 2^8 + 2^7 + 2^5 + 2^3 + 2^0) = -13,737\)
2’s complement: \(-(2^{14} + 2^{11} + 2^9 + 2^6 + 2^4 + 2^2 + 2^1 + 1) = -19,031\)