Search code examples
c++binaryfilesfwrite

writing a CString into a .bin file


I have a CString with 'HEX' values, which looks something like this: "0030303100314a"

Now I want to store this into a bin file, so that if I open it with a hex-editor, the data us displayed is displayed like in the string: 00 30 30 30 31 00 31 4a

I fail to prepare the data right. It gets always saved in standard ASCII even though I use the "wb" mode.

Thanks in advance


Solution

  • OK your misunderstanding is that "wb" means that all output happens in 'binary'. That's not what it does at all. There are binary output operations, and you should open the file in binary mode to use them, but you still have to use binary output operations. This also means you have to do the work to convert your hex characters to integer values.

    Here's how I might do your task

    for (int i = 0; i + 1 < str.GetLength(); i += 2)
    {
        int hex_value = 16*to_hex(str[i]) + to_hex(str[i+1]); // convert hex value
        fputc(hex_value, file);
    }
    
    static int to_hex(TCHAR ch)
    {
        return ch >= '0' && ch <= '9' ? ch - '0' : ch - ('A' - 10);
    }