开发者

How do I convert byte to string?

开发者 https://www.devze.com 2023-01-03 16:04 出处:网络
Is there any fast way 开发者_Python百科to convert given byte (like, by number - 65) to it\'s text hex representation?

Is there any fast way 开发者_Python百科to convert given byte (like, by number - 65) to it's text hex representation?

Basically, I want to convert array of bytes into (I am hardcoding resources) their code-representation like

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

How do I automate this Given byte -> "0x0A" string conversion?


In C++, you can use stringstream, and ssprintf.

Some compilers may have an itoa method that will convert an integer into its textual representation.

These are portable functions. You can always add an integer to '0' to get a textual digit and likewise with 'A' and 'a'.


From 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();
}


How about

#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] 
                  << " ";
    }
}


http://www.codeguru.com/forum/showthread.php?t=361158 ?


Thank you, just to mention, I used the following construction:

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

精彩评论

暂无评论...
验证码 换一张
取 消