5.11 Hexadecimal and Octal Constants

I l @ ve RuBoard

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 174 10 . Computers deal with binary (base 2) numbers: 10101110 2 . The octal (base 8) system easily converts to and from binary. Each group of three digits (2 3 = 8) can be transformed into a single octal digit. Thus 10101110 2 can be written as 10 101 110 and changed to the octal 256 8 . Hexadecimal (base 16) numbers have a similar conversion, but 4 bits at a time are used. For example, 10010100 2 is 1001 0100, or 94 16 .

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

Base 10

Base 8

Base 16

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); } 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net