开发者

Using C++ hex and cin

If you have the following code:

cout << hex << 10;

The output is 'a', which means the decimal 10 is converted into its hexadecim开发者_StackOverflowal 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?


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.


"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".


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜