至少有时将 uint8_t 强制转换为 signed int 是不正确的吗?

Is casting uint8_t to signed int at least sometimes incorrect?

在阅读以下问题的答案时

Getting a buffer into a stringstream in hex representation:

我不明白为什么有必要将 uint8_t 转换为 unsigned(或者,如评论中所写,甚至在此之前转换为 unsigned char),而只是转换为int 不正确。

据我了解,根本没有任何转换会导致将 uint8_t 解释为基础类型,它可以(必须?)是 3 char 变体中的一部分,因此将其打印为字符。

但是转换为 int 有什么问题?任何 uint8_t 值都应始终适合 int,因此转换似乎很简单。为什么符号扩展会使代码不正确(在评论中提到)?

UPD:

仅供参考,我认为我提到的问题中谈到的是 signed char:

的情况
signed char num = -1;
std::cout << std::hex << static_cast<unsigned int>(static_cast<unsigned char>(num));

在没有第二次演员表的情况下,这将被写为超过 2 f 秒。

关于 2 的补码系统的观点似乎是不正确的,因为整数转换应该适用于将 -1 转换为 unsigned <smth>,并且它遵循 2 的补码系统(即当转换为例如 uint8_t 结果应始终为 255,因此打印为 0xff,即使具有不同的位模式)。

你说得对,将 uint8_t 转换为 int 与将 uint8_t 转换为 unsigned int 产生的值完全相同。一个简单的循环来测试 uint8_t、0 ... 255 的所有可能值,将确认生成的字符串 100% 相同,并且假设所有实现都必须支持甚至高于 255 的 int 值,在 int 的有限范围可能会导致问题的情况下,不可能有一些晦涩的实现。