I have an integer, retrieved from a file using fscanf. How do I write this into a binary file as a two-byte integer in hex?
-
2That's a bit unspecific. In general you either write binary or you write text. 2 byte hex, as seen in hexeditors is just a form of displaying the binary values.Jules– Jules2010-11-23 00:11:03 +00:00Commented Nov 23, 2010 at 0:11
-
2'into a binary file as 2 byte integer in hex...' Sooo you want to take the integer you took from a binary file (which format.. assuming short as you want to store it in a 2-byte format) and want to write it back to binary format but in hex? That is a misunderstanding of how data is represented. Data in Hex is just another way to display (hexadecimal vs decimal vs octal etc...). Check out your windows calculator in scientific format. You will be able to switch between the different representations very easily and quickly. You can store the integer in TEXT format and show the hex representationg19fanatic– g19fanatic2010-11-23 00:15:31 +00:00Commented Nov 23, 2010 at 0:15
Add a comment
|
4 Answers
Do you mean you just want two bytes in the file like "\x20\x20" and not as text as in "0x2020"?
Assuming your variable is short. (sizeof(short) == 2)
First one: fwrite((const void*)&variable, sizeof(variable), 1, file);
Second one: fprintf(file, "%#06x", variable);
1 Comment
Jonathan Leffler
Don't you need "%#06x" - without the '#' it just prints 002020.