So I have a two char array
unsigned char v[2];
I want to show the value of v[0] as a number from 0 to 255 but
cout << v[0] << endl; //prints some garbage
cout << (void*)v[0] << endl; //prints the right thing but in hex
So I tried
cout << (int)v[0] << endl;
or
printf("%d\n", v[0]);
This shows exactly what I wanted but I don't like it at all. Also what I don't understand at all is why this doesn't work:
cout << reinterpret_cast<int>(v[0]) << endl; //compiler error
(In layman's terms) reinterpret_cast
is used to interpret the bits of an object as another type in an implementation-defined manner. You don't want that: you want a conversion (from char to int). Use static_cast
instead.
(All possible uses of reinterpret_cast
are listed in 5.2.10; this is not one of them.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With