tags:

views:

108

answers:

5

Hello!

Is there any fast way 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?

+2  A: 

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'.

Thomas Matthews
+1  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();
}
Fredrik Ullner
+1  A: 

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] 
                  << " ";
    }
}
Martin York
A: 

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();
HardCoder1986