0
votes

I would like to write short int x = 0x4740 to binary file in this form: 0100 0000 0100 0111 which is @G when i open it in notepad. It's working. When i try to write for example short int a = 0xf0ff; (binary: 1111 0000 1111 1111), notepad shows me ˙đ which is not really my number binary (˙đ is 1100 1011 1001 1001 1100 0100 1001 0001). How can write it and get 1111 0000 1111 1111 in this file?

Im using this converter: http://www.binaryhexconverter.com/binary-to-ascii-text-converter

int main() {

ofstream plik;
plik.open("D:\\book.dat", ios::binary);
if (!plik.good()) cout << "error";

short int x = 0xf0ff;

plik.write(reinterpret_cast<char*>(&x), 2);
plik.close();

system("pause");
return 0;
}    
2
Use a hex editor to see the contents of your file, not a text editor.Mat
"which is @G .. [therefore] it is working". The same is true for the observed "˙đ". Why do you believe there is a difference?Jongware
Well, the problem is a little bit more complicated. I'm calculating a CRC16 checksum from file. Let's say i got crc = 0xf0ff. When i write this to file and then again calculate the CRC16 i should get 0. Now the problem is that 0xf0ff is not really the 1111 0000 1111 1111.KRol
You can use a char pointer to that variable address in a for loop, up until you get to the size of that variable. Writing byte by byte.Zach P

2 Answers

2
votes

Your code will correctly write that number into that file, but you have to be aware that on most architecture nowadays numbers are stored in Little Endian.

That is, short int x = 0xf0ff; in memory is 0xff 0xf0, not 0xf0 0xff as you might expect.

Your text file will indeed contain 0xff 0xf0 if you try to open it with a hex editor. This is equivalent to 1111 1111 1111 0000 in binary (and not 1111 0000 1111 1111).

Then your text editor is interpreting 0xff 0xf0 as ˙đ.


Now if you want to write 1111 0000 1111 1111 in your file, you must write the number "in reverse" or use a char array directly :

short int x = 0xfff0 or char plik[] = {0xf0, 0xff};

Note that not all architectures are little endian, so if you care about portability, using a char array is recommended.

1
votes

Your code is ok. The interpretation of binary data with Notepad however is not. In short, you shouldn't use Unicode values for non-ASCII characters (like đ) when looking at the file with Notepad.

Notepad reads your file in a 8-bit encoding, using (presumably) codepage for non-Unicode programs which is configured in Windows Regional and Language Settings.

Now, in windows-1250 (I guess this is configured in your locale) đ has code 0xf0, and ˙ has code 0xff. So the file contents is 0xff 0xf0, which is exactly what you'd expect.

I'd suggest using some more advanced tool to examine contents of binary files.