reinterpret_cast: unsigned char to unsigned int

hello,

i have following code to print out the content of a pointer in hex and dec
1
2
3
4
5
6
7
8
9
10
11
std::ostringstream     msg;
msg.str("");
unsigned char value = 'F';
unsigned char *data;

data = &value;

msg<< "Data:                     " << endl
<< std::internal << std::setw( 8 ) << std::setfill( '0' ) 
<< std::uppercase << hex << *reinterpret_cast< unsigned int*>(data)
<< "\t -\t " << std::dec << *reinterpret_cast<unsigned int*>(data);


i was expecting this output:
 
Data			: 0x00000046	 -	 70


but i got the following one:
 
Data			: 0xCCCCCC46	 -	 3435973702


Why? Waht am i doing wrong?

Thank you for the help.
When you use

*reinterpret_cast< unsigned int*>(data)

the compiler takes into account all 4 bytes (for a 32-bit system) near the byte that contains the value of variable 'value'.

It would be more simply to write

static_cast<unsigned int>( *data )
Last edited on
char is one byte value. Int is 4 on your PC. When you do reinterpret_cast, it treats 1-byte pointer as 4 byte one, when you dereference it you 3 higher bytes of int have unknown data.
> Waht am i doing wrong?

You are causing undefined behaviour.

To get what you expected to get:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iomanip>

int main()
{
    unsigned char value = 'F' ;
    unsigned char *ptr = &value ;
    std::cout << std::hex << std::showbase << std::internal << std::setfill('0')
               << std::setw(10) << int(*ptr)
               << "\t - \t" << std::dec << int(*ptr) << '\n' ;
}
thank you very much
Topic archived. No new replies allowed.