0

I have an int which I want to convert to a char array, but I want the char array to be formatted in hexadecimal and with every byte of the int taking up exactly 2 char variables (filled out with zeroes).

To clarify what I mean, I have an example:

I want the int 232198 (0x38b06) to become "00038b06".

I can of course acomplish this by using this code:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << 
    std::hex << 
    std::setw(8) << 
    std::setfill('0') << 
    232198 <<
    std::endl;

    return 0;
}

Which prints out:

00038b06

But that only prints it out to the console, and as I mentioned before, want to store it a char array.

I don't care if the code is portable or not, this just has to work for windows.

1 Answers1

0

stringstreams are useful to do this:

std::stringstream sstr;
sstr << 
    std::hex << 
    std::setw(8) << 
    std::setfill('0') << 
    232198;
std::string str = sstr.str();

now str contains the formatted number. str.c_str() will give you a const char*.

alain
  • 11,939
  • 2
  • 31
  • 51