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?
Asked
Active
Viewed 5,712 times
1
-
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 Nov 23 '10 at 00: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 representation – g19fanatic Nov 23 '10 at 00:15
4 Answers
3
This will write a short integer to a binary file. The result is 2 bytes of binary data (Endianness dependent on the system).
int main(int argc, char* argv[])
{
short i;
FILE *fh;
i = 1234;
fh = fopen( argv[1], "wb" );
fwrite( &i, sizeof( i ), 1, fh );
fclose(fh);
}

Mark Wilkins
- 40,729
- 5
- 57
- 110
0
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);

Henry H
- 103
- 1
- 1
- 8
-
Don't you need "%#06x" - without the '#' it just prints 002020. – Jonathan Leffler Nov 23 '10 at 00:41