0

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

Andreas D.
  • 73
  • 1
  • 12
  • 1
    What is your question? Is your code not working? If so then post the code. – john Apr 19 '13 at 15:00
  • @john Will do on monday. I can't access it over the weekend. My question is how to convert the string, so I can save the data proberly into my bin file – Andreas D. Apr 19 '13 at 15:04

2 Answers2

2

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);
}
john
  • 7,897
  • 29
  • 27
  • Hi. I will try this at work tomorrow. I understand my fault now, but honestly I don't really get the to_hex() function. Even considering an Ascii table I couldn't figure out the exact use of the else-operation. – Andreas D. Apr 21 '13 at 20:00
  • Thank you very much! I used your solution and only needed to make a little change; An if-statement for upper-case letters. Else, random differences would occur in the saved file. – Andreas D. Apr 22 '13 at 06:05
  • @AndreasD. Yes I was assuming that all your letters were upper case. Glad it helped. – john Apr 22 '13 at 09:28
0

The program od will take a file and convert it to various representations. For example, if you say od -x myfile.bin, the contents of myfile.bin will be printed as hexadecimal bytes, just like what you're looking for. You could make C++ do this too, but maybe it's easier to just post-process your data to look the way you want.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436