Routing TCP[s]IP (Vol. 11998)

 

Working with Hexadecimal Numbers

Writing out binary octets isn't much fun. For people who must work with such numbers frequently, a briefer notation is welcome. One possible notation is to have a single character for every possible octet. However, there are 2 8 = 256 different combinations of eight bits, so a single-character representation of all octets would require 256 digits, or a base 256 numbering system.

Life is much easier if an octet is viewed as two groups of four bits. For instance, 11010011 can be viewed as 1101 and 0011. There are 2 4 = 16 possible combinations of four bits, so with a base 16, or hexadecimal, numbering system, an octet can be represented with two digits. (The root hex means "six," and deci means "ten.") Table A.1 shows the hexadecimal digits and their decimal and binary equivalents.

Table A.1. Hex, decimal, and binary equivalents.

Hex

Decimal

Binary

0000

1

1

0001

2

2

0010

3

3

0011

4

4

0100

5

5

0101

6

6

0110

7

7

0111

8

8

1000

9

9

1001

A

10

1010

B

11

1011

C

12

1100

D

13

1101

E

14

1110

F

15

1111

Because the first 10 characters of the decimal and the hexadecimal numbering system are the same, it is customary to precede a hex number with a 0x, or follow it with an h, to distinguish it from a decimal number. For example, the hex number 25 would be written as 0x25 or as 25h. This book uses the 0x convention.

After working with binary for only a short while, it is easy to determine a decimal equivalent of a four-bit binary number in your head. It is also easy to convert a decimal digit to a hex digit in your head. Therefore, converting a binary octet to hex is easily done in three steps:

  1. Divide the octet into two, four-bit binary numbers.

  2. Convert each four-bit number to decimal.

  3. Write each decimal number in its hex equivalent.

For example, to convert 11010011 to hex:

  1. 11010011 becomes 1101 and 0011.

  2. 1101 = 8 + 4 + 1 = 13, and 0011 = 2 + 1 = 3.

  3. 13 = 0xD, and 3 = 0x3.

Therefore, 11010011 in hex is 0xD3.

Converting from hex to binary is a simple matter of working the three steps backwards . For example, to convert 0x7B to binary:

  1. 0x7 = 7, and 0xB = 11.

  2. 7 = 0111, and 11 = 1011.

  3. Putting the four-bit numbers together, 0x7B = 01111011.

Категории