Using C ++ hex and cin

If you have the following code:

cout << hex << 10; 

The output is "a", which means that decimal 10 is converted to a hexadecimal value.

However, in the code below ...

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

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

I'm interested in the point where it became int. If it is broken, it will be:

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

Is it correct?

+4
source share
3 answers

The hex manipulator only controls how the value is read - it is always stored using the same internal binary representation. There is no way for the variable to β€œremember” that it was introduced in hex.

+8
source

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

+6
source

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

+6
source

Source: https://habr.com/ru/post/1303248/


All Articles