Question:
C++ why won't these convert to hex?
Michael Quirk
2010-10-24 14:13:34 UTC
Hey simple question, I need to print out the variable, the address of the variable, and the hex of the variable. Why won't the conversion work? the 'hex' manipulator is supposed to set the basefield of the stream to base 16 but I am just getting the same values as the original value.

#include
#include
#include
using namespace std;

int main()
{

double x =5.1;
int y = 9;
string z = "Hello";

cout << x << " Address: "<< &x << " Hex: " << hex << x << endl;
cout << y << " Address: "<< &y <<" "<< " Hex: " << hex << y << endl;
cout << z << " Address: "<< &z << " " << " Hex: " << hex << z << endl;

system("pause");
return 0;
}
Three answers:
siamese_scythe
2010-10-24 14:16:18 UTC
I think it's because:



5.1 is not an integer

9 in hex is still 9

"Hello" is not an integer
husoski
2010-10-24 22:22:21 UTC
There's a small problem here. First, hex output only applies to integer types (char, short, int, long, and the unsigned versions of those). If you have to display a hexadecimal representation of floating point or string data, you need to write some code.



Second, hex is sticky. One you "output" it to a stream it stays set until you reverse it. This is one of the many unlovely things about cout << for formatted output. To see what I mean, change the value for y from 9 to something bigger, like 42042, and you'll see that it actually displays as a43a, even when you thought you were displaying it in decimal.



Add "<< dec" just before each "<< endl" and you should get y displaying normally.



Third, it appears that pointers are formatted in uppercased hexadecimal with leading zeros no matter what you do. If this is the only thing you needed "hex" for, then you don't need it at all.



Finally, no...there's no "0x" on output. If you want that, you need to add it yourself.
?
2010-10-25 01:31:51 UTC
To make an integer "start out in 0x", apply the IO manipulator std::showbase.



If you intended to output the values of the pointers in decimal, you will have to cast them to an appropriate integral type. No need to use std::hex / std::dec, since they have no effect on most implementation's output of pointers anyway (it is unspecified by the standard, and different compilers handles it differently)



     cout << x << " Address: " << (uintptr_t)(&x) << " Hex: " << &x << '\n'

         << y << " Address: "<< (uintptr_t)(&y) << " Hex: " << &y << '\n'

         << z << " Address: "<< (uintptr_t)(&z) << " Hex: " << &z << endl;



(uintptr_t comes from stdint.h / cstdint if supported)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...