c++asciihexofstream

How does one write the hex values of a char in ASCII to a text file?


Here is what I currently have so far:

void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
    unsigned char *buf = (unsigned char*)ptr;

    for( int i = 0; i < buflen; ++i ) {
        if( i % 16 == 0 ) {
            stream << prefix;
        }

        stream << buf[i] << ' ';
    }
}

I've tried doing stream.hex, stream.setf( std::ios::hex ), as well as searching Google for a bit. I've also tried:

stream << stream.hex << (int)buf[i] << ' ';

But that doesn't seem to work either.

Here is an example of some output that it currently produces:

Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 

I would like the output to look like the following:

FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00

Solution

  • #include <iostream>
    int main() {
        char c = 123;
        std::cout << std::hex << int(c) << std::endl;
    }
    

    Edit: with zero padding:

    #include <iostream>
    #include <iomanip>
    int main() {
        char c = 13;
        std::cout << std::hex << std::setw(2) << std::setfill('0') << int(c) << std::endl;
    }