C++: From byte to signed int
If we cast a byte, that is, an unsigned char, to and int, we'll get a value between 0 and 255, since int, even thpugh it's signed, contains that range of values.
If our intention is to see that byte as a value between -128 and 127, we must cast to signed char before casting to int. So watch it.
unsigned char b = 248;
int i = static_cast<int>(b); //248
int j = static_cast<int>( static_cast<char>(b) ); //-8
I prefer using static_cast to the traditional, equivalent casting style because it makes casts easier to find when you suspect there is a problem caused by them. (it's easier to find "static_cast<int>" than "(int)" )
Comments
Post a Comment