5.11 Hexadecimal and Octal Constants
Integer
numbers are specified as a string of digits, such as 1234, 88, -123,
and so on. These are decimal (base 10) numbers: 174 or
17410. Computers deal with binary (base 2)
numbers: 101011102. The octal (base 8) system
easily converts to and from binary. Each group of three digits
(23 = 8) can be transformed into a single
octal digit. Thus 101011102 can be written as
10 101 110 and changed to the octal 2568.
Hexadecimal (base 16) numbers have a similar conversion, but 4 bits
at a time are used. For example, 100101002 is
1001 0100, or 9416.
The C++ language has conventions for representing octal and
hexadecimal values. Leading zeros are used to signal an octal
constant. For example, 0123 is 123 (octal) or 83 (decimal). Starting
a number with "0x" indicates a
hexadecimal (base 16) constant. So 0x15 is 21 (decimal). Table 5-3 shows several numbers in all three bases.
Table 5-3. Integer examples
6
|
06
|
0x6
|
9
|
011
|
0x9
|
15
|
017
|
0xF
|
23
|
027
|
0x17
|
Question 5-3: Why does the following program fail to print the correct Zip code?
What does it print instead?
#include <iostream>
long int zip; // Zip code
int main( )
{
zip = 02137L; // Use the Zip code for Cambridge MA
std::cout << "New York's Zip code is: " << zip << '\n';
return(0);
}
|