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

2022-01-12 00:00:00 formatting c++ ostream

我想在 C++ 中使用无符号 8 位变量.就算术而言,unsigned charuint8_t 都可以解决问题(这是预期的,因为 AFAIK uint8_t 只是 uint8_t 的别名code>unsigned char,或者调试器显示它.

I want to work with unsigned 8-bit variables in C++. 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, or so the debugger presents it.

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

The problem is that if I print out the variables using ostream in C++ it treats it as char. If I have:

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,但正如我之前提到的,它的 typedef'ed 为 unsigned char,所以它也是如此.如何正确打印我的变量?

I tried using uint8_t, but as I mentioned before, that's typedef'ed to unsigned char, so it does the same. How can I print my variables correctly?

我在我的代码中的很多地方都这样做了.每次我想打印时,有什么方法可以在 不 强制转换为 int 的情况下做到这一点?

I do this in many places throughout my code. Is there any way I can do this without casting to int each time I want to print?

推荐答案

我建议使用以下技术:

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;
}

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

It's short to write, has the same efficiency as the original solution and it lets you choose to use the "original" character output. And it's type-safe (not using "evil" macros :-))

相关文章