问题
While reading the answer to the following question
Getting a buffer into a stringstream in hex representation:
I did not understand why there is a necessity to cast uint8_t
to unsigned
(or, as written in comments, even to unsigned char
before that), while casting just to int
is incorrect.
As I understand, no conversions at all would lead to interpreting uint8_t
as an underlying type which can (must?) be some of 3 char
variations and thus printing it as a character.
But what's wrong with casting to int
? Any uint8_t
value should always fit in int
, so the conversion seems to be straightforward. Why sign-extension would make the code incorrect (mentioned in comments)?
UPD:
Just for reference, I figured what was talked about in the question I referred to is a case for signed char
:
signed char num = -1;
std::cout << std::hex << static_cast<unsigned int>(static_cast<unsigned char>(num));
This would be written as more than 2 f
s in absence of the second cast.
The point about 2's complement system seems to be incorrect though, as an integral conversion should apply to convert -1 to unsigned <smth>
, and it adheres to the 2's complement system (i.e. when converting to e.g. uint8_t
the result should always be 255 and thus be printed as 0xff
, even having a different bit pattern).
回答1:
You are correct that casting uint8_t
to int
will produce the exact same value as casting uint8_t
to unsigned int
. A simple loop to test all possible values of uint8_t
, 0 ... 255, will confirm that the generated strings are 100% identical, and given that all implementations must support int
values even higher than 255, there is no chance of some obscure implementation where limited range of int
might cause problems.
来源:https://stackoverflow.com/questions/44892781/is-casting-uint8-t-to-signed-int-at-least-sometimes-incorrect