将uint8_t强制转换为带符号的int至少有时是不正确的吗? [英] Is casting uint8_t to signed int at least sometimes incorrect?
问题描述
在阅读以下问题的答案时
While reading the answer to the following question
我不明白为什么必须将 uint8_t
强制转换为 unsigned
(或者如注释中所述,甚至转换为 unsigned char
之前),而仅强制转换为 int
是不正确的.
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.
据我所知,根本没有转换会导致将 uint8_t
解释为基础类型,该类型可以(必须?)为3个 char
变体中的一部分,从而进行打印作为角色.
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.
但是强制转换为 int
有什么问题?任何 uint8_t
值都应始终适合 int
,因此转换似乎很简单.为什么用符号扩展名会使代码不正确(在注释中提到)?
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));
在没有第二次强制转换的情况下,这将被写成2个以上的 f
.
This would be written as more than 2 f
s in absence of the second cast.
关于2的补码系统的观点似乎是不正确的,因为积分转换应适用于将-1转换为 unsigned< smth>
,并且它遵循2的补码系统(即转换为 uint8_t
的结果应始终为255,因此即使具有不同的位模式,也应打印为 0xff
.
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).
推荐答案
您正确的是,将 uint8_t
强制转换为 int
会产生与强制转换完全相同的值uint8_t
转换为 unsigned int
.一个简单的循环来测试 uint8_t
的所有可能值(0 ... 255),将确认生成的字符串是100%相同的,并且假定所有实现都必须支持 int
值甚至高于255,就不可能有一些晦涩的实现,因为有限的 int
范围可能会引起问题.
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.
这篇关于将uint8_t强制转换为带符号的int至少有时是不正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!