I l @ ve RuBoard |
Computer workers often use number systems based on 8 and on 16. Because 8 and 16 are powers of 2, these systems are more closely related to a computer's binary system than the decimal system is.
Octal refers to a base 8 system. In this system, the different places in a number represent powers of 8. You use the digits 0 to 7. For example, the octal number 451 (written 0451 in C) represents this:
4 x 8 2 + 5 x 8 1 + 1 x 8 = 297 (base 10)
A handy thing to know about octal is that each octal digit corresponds to three binary digits. Table 15.1 shows the correspondence. This correspondence makes it simple to translate between the two systems. For example, the octal number 0377 is 11111111 in binary. We replaced the 3 with 011, dropped the leading 0, and then replaced each 7 with 111. The only awkward part is that a 3-digit octal number might take up to 9 bits in binary form, so an octal value larger than 0377 requires more than a byte. Note that internal 0s are not dropped: 0173 is 01 111 011, not 01 111 11.
Octal Digit | Binary Equivalent |
---|---|
000 | |
1 | 001 |
2 | 010 |
3 | 011 |
4 | 100 |
5 | 101 |
6 | 110 |
7 | 111 |
Hexadecimal (or "hex") refers to a base 16 system. Here you use powers of 16 and the digits 0 to 15, but because you don't have single digits to represent the values 10 to 15, use the letters A to F for that purpose. For instance, the hex number A3F (written 0xA3F in C) represents
10 x 16 2 + 3 x 16 1 + 15 x 16 = 2623 (base 10)
because A represents 10 and F represents 15. In C, you can use either lowercase or uppercase letters for the additional hex digits. Therefore, you can also write 2623 as 0xa3f .
Each hexadecimal digit corresponds to a 4-digit binary number, so two hexadecimal digits correspond exactly to an 8-bit byte. The first digit represents the upper 4 bits, and the second digit the last 4 bits. This makes hexadecimal a natural choice for representing byte values. Table 15.2 shows the correspondence. For example, the hex value 0xC2 translates to 11000010.
Decimal Digit | Hexadecimal Digit | Binary Equivalent | Decimal Digit | Hexadecimal Digit | Binary Equivalent |
---|---|---|---|---|---|
0000 | 8 | 8 | 1000 | ||
1 | 1 | 0001 | 9 | 9 | 1001 |
2 | 2 | 0010 | 10 | A | 1010 |
3 | 3 | 0011 | 11 | B | 1011 |
4 | 4 | 0100 | 12 | C | 1100 |
5 | 5 | 0101 | 13 | D | 1101 |
6 | 6 | 0110 | 14 | E | 1110 |
7 | 7 | 0111 | 15 | F | 1111 |
Now that you've seen what bits and bytes are, let's examine what C can do with them. C has two facilities to help you manipulate bits. The first is a set of six bitwise operators that act on bits. The second is the field data form, which gives you access to bits within an int. The following discussion outlines these C features.
I l @ ve RuBoard |