Is casting uint8_t to signed int at least sometimes incorrect?

落爺英雄遲暮 提交于 2021-02-10 14:19:30

问题


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 fs 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!