如何在c ++中使用ostream打印一个unsigned char作为hex? [英] how do I print an unsigned char as hex in c++ using ostream?
问题描述
我想使用C ++中的无符号8位变量。 unsigned char
或 uint8_t
就算法而言,这样做是有道理的(这是预期的,因为AFAIK uint8_t
只是 unsigned char
的别名,因此调试器会显示它。
$ b如果我有:
<$ c如果我在c ++中使用ostream打印输出变量$ c> unsigned char a = 0;
unsigned char b = 0xff;
cout<<a is<<<<<< <<< hex<< b<< endl;
:
a是^ @; b是377
而不是
a是0; b是ff
我尝试使用 uint8_t
,但正如我之前提到的,typedef unsigned char
,所以它也是这样的。如何正确打印我的变量?
编辑:我在我的代码中的很多地方这样做。是否有任何方式,我可以做这个没有每次我想要打印 c
我建议使用以下技术:
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<
}
inline HexCharStruct hex(unsigned char _c)
{
return HexCharStruct(_c);
}
int main()
{
char a = 131;
std :: cout<< hex(a)<< std :: endl;
}
这是写入的简短,具有与原始解决方案相同的效率,您选择使用原始字符输出。它是类型安全的(不使用邪恶宏: - ))
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.
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;
then the output is:
a is ^@; b is 377
instead of
a is 0; b is ff
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?
Edit: 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?
I would suggest using the following technique:
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 :-))
这篇关于如何在c ++中使用ostream打印一个unsigned char作为hex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!