如何将整数转换为存储在char数组中的十六进制字节?

时间:2017-05-01 21:42:53

标签: c++ arrays int hex type-conversion

我目前正在处理一个整数,它将适合一个十六进制字节,作为字符数组中的十六进制值。例如,我的输入将是:

int i = 28;

输出结果如下:

char hex[1] = {'\x1C'};

最简单的方法是什么?

2 个答案:

答案 0 :(得分:2)

char hex[1] = {i};

就是这样。

为避免出现有关缩小转化次数的警告,您也可以转为char

没有“十六进制字节”这样的东西;只有一个字节。当您在源代码中将其写为文字时,它只是“十六进制”。与其他所有值一样,它不会以十六进制或十进制存储在您的计算机上,而是以二进制形式存储。

所以,基数是无关紧要的。你已经拥有了这个价值。把它放在数组中。

答案 1 :(得分:-1)

这种方式 使用std::stringstream将整数转换为字符串及其特殊操纵符来设置基数。例如:

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();

OR

Use <iomanip>'s std::hex.如果您打印,只需将其发送至std::cout,如果没有,则使用std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first << with << "0x" 
如果你愿意,可以随心所欲。

其他感兴趣的信息是std::oct (octal)std::dec(返回小数)。

您可能遇到的一个问题是,这会产生表示它所需的确切数字位数。你可以使用setfill和setw来解决这个问题:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;
So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}