Hexadecimal

Motivation: Easy Convertion

Computers work with binary numbers, but humans don't. We humans are used to decimal numbers, but the "binary-decimal" is not a natural idea. A better option is using hexadecimal numbers, or simply hex. Why hex? Take a look at the following convertions:

DecimalBinaryHex

0

0000

0

1

0001

1

2

0010

2

3

0011

3

4

0100

4

5

0101

5

6

0110

6

7

0111

7

8

1000

8

9

1001

9

10

1010

A

11

1011

B

12

1100

C

13

1101

D

14

1110

E

15

1111

F

16

0001 0000

10

17

0001 0001

11

55

0011 0111

37

195

1100 0011

C3

Key Ideas:

  • 1 hex digit <=> 4 bits.

  • For a long binary string, we can pad 0's on the left to some multiples of 4 and divide the binary string into chunks of length 4. For example, 10001 can be padded as 00010001 and divided into two chunks 0001 0001.

  • 1 byte <=> 2 hex digits. The convertion is easy enough, even for humans.

Binary => Decimal

For example, convert 0b10110001 to decimal. From right to left:

  • 1 => 1 * 2^0 = 1

  • 0 => 0 * 2^1 = 0 (skipped)

  • 0 => 0 * 2^2 = 0 (skipped)

  • 0 => 0 * 2^3 = 0 (skipped)

  • 1 => 1 * 2^4 = 16

  • 1 => 1 * 2^5 = 32

  • 0 => 0 * 2^6 = 0 (skipped)

  • 1 => 1 * 2^7 = 128

Therefore 0b10110001 = 1 + 16 + 32 + 128 = 177.

Decimal => Binary

For example, convert 26 to binary:

  • 26 / 2 = 13 ...... 0

  • 13 / 2 = 6 ...... 1

  • 6 / 2 = 3 ...... 0

  • 3 / 2 = 1 ...... 1

  • 1 / 2 = 0 ...... 1 (algorithm terminates)

Therefore 26 = 0b11010.

Hex => Decimal

For example, convert 0x125 to decimal. From right to left:

  • 5 => 5 * 16^0 = 5

  • 2 => 2 * 16^1 = 32

  • 1 => 1 * 16^2 = 256

Therefore 0x125 = 5 + 32 + 256 = 293.

Decimal => Hex

For example, convert 293 to hex:

  • 293 / 16 = 18 ...... 5

  • 18 / 16 = 1 ...... 2

  • 1 / 16 = 0 ...... 1

Therefore 293 = 0x125.

Last updated