如何将字节转换为字符串?

时间:2010-06-14 19:57:30

标签: c# c++

有没有快速方法将给定字节(例如,按数字 - 65)转换为文本十六进制表示?

基本上,我想将字节数组转换为(我是硬编码资源)它们的代码表示,如

BYTE data[] = {0x00, 0x0A, 0x00, 0x01, ... }

如何自动执行此Given byte -> "0x0A" string转换?

5 个答案:

答案 0 :(得分:3)

在C ++中,您可以使用stringstream和ssprintf。

某些编译器可能会使用itoa方法将整数转换为其文本表示形式。

这些是便携式功能。您始终可以将整数添加到“0”以获取文本数字,同样使用“A”和“a”。

答案 1 :(得分:2)

来自http://www.leunen.com/cbuilder/convert.html;

template<class T>
std::string ToHex(const T &value)
{
  std::ostringstream oss;
  if(!(oss<<std::hex<<value))
     throw exception("Invalid argument");
  return oss.str();
}

答案 2 :(得分:2)

怎么样

#include <iostream>
#include <iomanip>

typedef int BYTE;


int main()
{

    BYTE data[] = {0x00, 0x0A, 0x00, 0x01 };

    for(int loop=0;loop < 4; ++loop)
    {
        std::cout << "Ox" 
                  << std::setw(2) 
                  << std::setfill('0') 
                  << std::hex 
                  << data[loop] 
                  << " ";
    }
}

答案 3 :(得分:1)

答案 4 :(得分:1)

谢谢,就提一下,我使用了以下结构:

std::stringstream stream;
for (size_t i = 0; i < size; ++i) {
   stream << "0x" << std::hex << (short)data[i] << ", ";
}
std::string result = stream.str();