将十六进制值 FF 存储在无符号 8 位整数中会产生垃圾而不是 -1

Storing the hex value FF in an unsigned 8 bit integer produces garbage instead of -1

看我的代码:

#include <iostream>

int main()
{
  uint8_t no_value = 0xFF;
  std::cout << "novalue: " << no_value << std::endl;
  return 0;
}

为什么会这样输出:novalue:▒

在我的终端上看起来像:

我期待-1。

毕竟,如果我们:

我们得到:

uint8_t 最有可能 typedef-ed 到 unsigned char。当您将其传递给 << 运算符时,会选择 char 的重载,这会导致您的 0xFF 值被解释为 ASCII 字符代码,并显示 "garbage" .

如果你真的想看到-1,你应该试试这个:

#include <iostream>
#include <stdint.h>

int main()
{
  uint8_t no_value = 0xFF;
  std::cout << "novalue (cast): " << (int)(int8_t)no_value << std::endl;
  return 0;
}

请注意,我首先强制转换为 int8_t,这会导致您之前的无符号值被解释为有符号值。这就是 255 变为 -1 的地方。然后,我转换为 int,以便 << 将其理解为 "integer" 而不是 "character"。

您的困惑来自于 Windows 计算器没有为您提供有符号/无符号选项——它总是考虑有符号的值。因此,当您使用 uint8_t 时,您将其设为无符号。

试试这个

#include <iostream>

int main()
{
  uint8_t no_value = 0x41;
  std::cout << "novalue: " << no_value << std::endl;
  return 0;
}

你会得到这个输出:

novalue: A

uint8_t 可能与 unsigned char 相同。 std::cout with chars 将输出 char 本身而不是 char 的 ASCII 值。