static_cast<>()

Started by
1 comment, last by KingofNoobs 11 years, 4 months ago
Hello,

In the following code I modified the isLittleEndian() version to eliminate the bitmask. I understand that the function of the bitmask is to zero out any bits on the unsigned (int) that are not used. But the strange thing is that if I leave out this bitmask, the output will insert 3 bytes of 0xffffff for every unsigned (int) printed to the stringstream.

This leads to my question. If static_cast<>()ing to a larger type does C++ or GCC fill the extra bits in with all 1s? I don't know why this would be the case but it seems to be.


template <class T>
std::string type_to_hex( const T arg )
{
std::ostringstream hexstr ;
const char* addr = reinterpret_cast<const char*>(&arg) ;
hexstr << "0x" ;
hexstr << std::setw(2) << std::setprecision(2) << std::setfill('0') << std::hex ;
if( isLittleEndian() )
{
for( int b = sizeof(arg) - 1; b >= 0; b-- )
{
hexstr << static_cast<unsigned>(*(addr+b)) ;
std::cout << hexstr.str() << std::endl;
}
}
else
{
for( int b = 0; b < sizeof(arg); b++ )
{
hexstr << static_cast<unsigned>(*(addr+b) & 0xff) ;
}
}
return hexstr.str() ;
}

int main()
{
std::cout << type_to_hex((float)16/9) << std::endl;
}


Output:
0x3f
0x3fffffffe3
0x3fffffffe3ffffff8e
0x3fffffffe3ffffff8e39
0x3fffffffe3ffffff8e39

I wonder as I wander...

http://www.davesgameoflife.com

Advertisement
The type const char is likely signed on your machine. Two's complement signed integers will sign-extend the value when widening to a larger type. Sign extension in two's complement counting systems will propagate the highest bit's state to all of the bits above it.

In this case, widening from signed 8bit to unsigned 32bit (depending on the compiler) copies the highest of the 8 bits into the 24 higher bits in the unsigned int.

Edit for example:

1st step: 0x3f is 00111111. The highest is 0, so zeroes are copied to the higher bits.
String is now 0x3f
2nd step: 0xe3 is 11100011. The highest is 1, so ones are copied to the higher bits.
String is now 0x3f ffffffe3
3rd step: 0x8e is 10001110. The highest is 1, so ones are copied to the higher bits.
String is now 0x3f ffffffe3 ffffff8e
4th step: 0x39 is 00111001. The highest is 0, so zeroes are copied to the higher bits.
String is now 0x3f ffffffe3 ffffff8e 39

At the end, this is the string:
0x3f ffffffe3 ffffff8e 39

Take care that you handle zeroes properly; a zero byte encountered in the number should be outputted if it isn't a leading zero.
Very insightful Ectara. Thank you very much.

I wonder as I wander...

http://www.davesgameoflife.com

This topic is closed to new replies.

Advertisement