简体   繁体   中英

Writing int to binary file

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;
}    

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM