views:

308

answers:

3

If you have the following code:

cout << hex << 10;

The output is 'a', which means the decimal 10 is converted into its hexadecimal value.

However, in the code below...

int n;
cin >> hex >> n;
cout << n << endl;

When input is 12, the output becomes 18. Can anyone explain the details of the conversion? How did it became a decimal value?

I'm interested in the point where it became an int. If broken down, it would be:

(( cin >> hex ) >> n);

Is this correct?

+6  A: 

"12" in hex is "18" in decimal. When you put in "12" into a hex cin stream, the internal value is 18 decimal. When you output to a stream which is by default decimal, you see the decimal value - "18".

Dominic Rodger
@Dominic: If I'm not mistaken, the input is treated as a hex which is 12 and then...? I don't know which part caused it to be converted into 18. Is it when storing it into n? When a hex value of 12 is stored into an n, it is automatically stored as 18?
jasonline
As Neil said, it's interpreted as a hex value, and stored as binary. The value of the characters "12" when interpreted as hex is 18 in decimal. It might help you to understand this if instead of `cout << n << endl` you run `cout << hex << n << endl;`
Dominic Rodger
+6  A: 

It reads 0x12 (a hex value) and stores it in n, which you then print in decimal. Variables simply contain values, they do not contain information about the base (actually they store everything in base 2).

Tronic
+8  A: 

The hex manipulator only controls how a value is read - it is always stored using the same internal binary representation. There is no way for a variable to "remember" that it was input in hex.

anon
@Neil: You mean during "cin >> hex" it is still 12 but when stored in the variable n, it was stored in its decimal value? It was implicitly converted to a decimal. Is that it?
jasonline
@jasonline When it was read, it was read as two character "1" and "2" - the iostream library converted these to a number, treating them as hex digits, so the value they represented was 16*1 + 2. This was then stored as a binary number with the decimal value of 18.
anon
@jasonline: When an int is read it's always converted to (stored as) binary. `hex` etc. just change what it is converted from. When you *output* it, it's converted to decimal (or hex if you use the `hex` modifier).
sepp2k