Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C++中转换Prttf的方式_C++_Hex_Printf - Fatal编程技术网

在C++中转换Prttf的方式

在C++中转换Prttf的方式,c++,hex,printf,C++,Hex,Printf,我有一个无符号字符,我想转换成十六进制。我知道printf%02X,char给了我想要的输出,但它被发送到终端,因此用处不大。如何将字符转换为十六进制,并像printf那样将其存储在变量中?例如,使用sprintf将其替换为缓冲区 char str[50]; sprintf(str, "%X02", char); 比如说: stringstream ss; ss << std::hex << std::setw(2) << (unsigned int) x;

我有一个无符号字符,我想转换成十六进制。我知道printf%02X,char给了我想要的输出,但它被发送到终端,因此用处不大。如何将字符转换为十六进制,并像printf那样将其存储在变量中?

例如,使用sprintf将其替换为缓冲区

char str[50];
sprintf(str, "%X02", char);

比如说:

stringstream ss;
ss << std::hex << std::setw(2) << (unsigned int) x;

cout << ss.str() << endl;

不过,您可能需要进一步调整stringstream。

请注意:您不是将其转换为十六进制值,而是转换为以null结尾的字符串。将其存储在模型的变量中是毫无意义的。

可能是最快的一个

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

嗯,用sprintf而不是printf?@mamills-当然,我只是举个例子。正如Mooing Duck所说,您应该使用snprintf来阻止缓冲区溢出。@mamills-50个字符,如示例中所示,对于该sprintf调用总是足够大。不要因为害怕未知而用复杂的代码替换简单的代码。谢谢!这是一个伟大而简单的解决方案,完全满足了我的需要。如果x的类型为unsigned char,这将不起作用。你必须明确地把X转换成int或其他非字符类型。我这样做的方法是用我有限的C++知识来做SS@ JAMESKANZE,我甚至没有想到用户定义的机械手:这是下一步。您已经有了正确的基本想法,尽管在实际应用程序中,保留十六进制集是非常不友好的——下一位输出整数的代码将非常令人惊讶。下一步是将常用的格式合并到一个用户定义的操纵器中,这样您就不必一直重复相同的操作。他正在使用%02X进行格式化。这意味着他必须传递一个int或unsigned,或者行为未定义,并且该值将被解释为unsigned。整数提升意味着任何字符类型都将转换为int。在他的代码中,您在哪里看到任何以null结尾的字符串的提示?