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

Try:

#include <iomanip>
....
stream << std::hex << static_cast<int>(buf[i]);

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

Edit: with zero padding:

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

char upperToHex(int byteVal)
{
    int i = (byteVal & 0xF0) >> 4;
    return nibbleToHex(i);
}

char lowerToHex(int byteVal)
{
    int i = (byteVal & 0x0F);
    return nibbleToHex(i);
}

char nibbleToHex(int nibble)
{
    const int ascii_zero = 48;
    const int ascii_a = 65;

    if((nibble >= 0) && (nibble <= 9))
    {
        return (char) (nibble + ascii_zero);
    }
    if((nibble >= 10) && (nibble <= 15))
    {
        return (char) (nibble - 10 + ascii_a);
    }
    return '?';
}

More code here.


You can also do it using something a bit more old-fashioned:

char buffer[4];//room for 2 hex digits, one extra ' ' and \0
sprintf(buffer,"%02X ",onebyte);