[英]Convert unsigned char the way printf does in C++
I have an unsigned char
that I want to convert to hexadecimal. 我有一个要转换为十六进制的unsigned char
。 I know printf("%02X", char)
gives me the output I want, but it is sent to the terminal and is thus of little use. 我知道printf("%02X", char)
给我我想要的输出,但是它被发送到终端,因此几乎没有用。 How can I convert the character to hexadecimal and store it in a variable the same way printf does it? 如何将字符转换为十六进制并将其存储在变量中,就像printf一样?
How about something like: 怎么样:
stringstream ss;
ss << std::hex << std::setw(2) << (unsigned int) x;
cout << ss.str() << endl;
You might want to tweak the stringstream
some more though. 您可能想进一步调整stringstream
。
Use sprintf
instead into a buffer, for example 例如,使用sprintf
代替缓冲区
char str[50];
sprintf(str, "%X02", char);
Maybe the fastest one? 也许最快的一个?
struct hex_uchar {
hex_uchar(unsigned char c)
{
value[0] = hc[c >> 4];
value[1] = hc[c & 0xF];
value[2] = '\0';
}
char value[3];
static char hc[16];
};
char hex_uchar::hc[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
int main() {
std::cout << hex_uchar('A').value << std::endl;
}
Pay attention: you are not converting it to hex value, you are converting to a null terminated string. 请注意:您没有将其转换为十六进制值,而是转换为以null终止的字符串。 Store it in a variable of your model is kind of nonsense. 将其存储在模型的变量中是胡说八道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.