如何使用 ostream 在 c 中将 unsigned char 打印为十六进制?

新手上路,请多包涵

我想在 C++ 中使用无符号的 8 位变量。 Either unsigned char or uint8_t do the trick as far as the arithmetic is concerned (which is expected, since AFAIK uint8_t is just an alias for unsigned char ,或者调试器呈现它。

问题是,如果我在 C++ 中使用 ostream 打印出变量,它会将其视为 char。如果我有:

 unsigned char a = 0;
unsigned char b = 0xff;
cout << "a is " << hex << a <<"; b is " << hex << b << endl;

那么输出是:

 a is ^@; b is 377

代替

a is 0; b is ff

我尝试使用 uint8_t ,但正如我之前提到的,它的类型定义为 unsigned char ,所以它也是一样的。如何正确打印我的变量?

编辑: 我在我的代码中的很多地方都这样做。有什么办法可以做到这一点 ,而无需 每次我想打印时都转换为 int

原文由 Nathan Fellman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 734
2 个回答

我建议使用以下技术:

 struct HexCharStruct
{
  unsigned char c;
  HexCharStruct(unsigned char _c) : c(_c) { }
};

inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& hs)
{
  return (o << std::hex << (int)hs.c);
}

inline HexCharStruct hex(unsigned char _c)
{
  return HexCharStruct(_c);
}

int main()
{
  char a = 131;
  std::cout << hex(a) << std::endl;
}

它写起来很短,与原始解决方案具有相同的效率,并且可以让您选择使用“原始”字符输出。而且它是类型安全的(不使用“邪恶”宏:-))

原文由 MartinStettner 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 C++20 中,您将能够使用 std::format 来执行此操作:

 std::cout << std::format("a is {:x}; b is {:x}\n", a, b);

输出:

 a is 0; b is ff

同时您可以使用 {fmt} 库std::format 是基于的。 {fmt} 还提供了 print 函数,这使得这更容易和更有效( 天螺栓):

 fmt::print("a is {:x}; b is {:x}\n", a, b);

免责声明:我是 {fmt} 和 C++20 std::format 的作者。

原文由 vitaut 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题