1

我有一个十六进制数组,我需要将其转换为字符串。

我的数组:

// declaration
unsigned char HEX_bufferMessage[12];

// initialize
    HEX_bufferMessage[0] = 0xF0;
    HEX_bufferMessage[1] = 0x15;
    HEX_bufferMessage[2] = 0x31;
    HEX_bufferMessage[3] = 0x02;
    HEX_bufferMessage[4] = 0x03;
    HEX_bufferMessage[5] = 0x00;
    HEX_bufferMessage[6] = 0x00;
    HEX_bufferMessage[7] = 0xD1;
    HEX_bufferMessage[8] = 0xD1;
    HEX_bufferMessage[9] = 0x00;
    HEX_bufferMessage[10] = 0x00;
    HEX_bufferMessage[11] = 0xF7;

我只有十六进制格式的这些信息,我需要将它们转换为字符串。有谁知道我该怎么做??

谢谢!!

4

6 回答 6

3

派对迟到了,但由于使用的所有答案std::to_string()都无法将十六进制值输出为十六进制值,我建议您将它们发送到流中,您可以通过以下方式格式化输出std::hex

std::cout << "0x" << std::hex << HEX_bufferMessage[0] << std::endl;

或者,如果您想在字符串中使用它:

std::string to_hex_string( const unsigned int i ) {
    std::stringstream s;
    s << "0x" << std::hex << i;
    return s.str();
}

甚至在一行中:

// ...
return (static_cast<std::stringstream const&>(std::stringstream() << "0x" << std::hex << i)).str();
于 2015-01-20T15:35:55.820 回答
2
std::bitset<16> foo(HEX_bufferMessage[0]);
std::string s = foo.to_string();

http://en.cppreference.com/w/cpp/utility/bitset/to_string

于 2013-11-01T11:51:51.997 回答
1

像这样的东西?

const char *hex = "0123456789ABCDEF";

unsigned char x = 0xF8;

std::cout << "0x" << hex[x >> 4 & 0xF] << hex[x & 0xF] << std::endl;
于 2013-11-01T11:50:59.260 回答
1

利用 :std::to_string

for (size_t i =0 ; i<10; ++i)
{
   std::string s { std::to_string(HEX_bufferMessage[i]) }; //ith element
   std::cout << s; //concatenate all s as per need
}
于 2013-11-01T11:42:52.640 回答
0

怎么样std::to_string

喜欢

std::string s;
for (auto const& v : HEX_bufferMessage)
    s += std::to_string(v);
于 2013-11-01T11:43:30.000 回答
0
char hex_string[12*2+1]; /* where 12 - is the number of you hex values, 2 - is 2 chars per each hex, and 1 is the final zero character */

for(int i=0;i<12;++i) {
  sprintf(hex_string+i*2,"%x", HEX_bufferMessage[i]);
}
于 2013-11-01T11:58:17.473 回答