Reputation: 25628
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?
Upvotes: 1
Views: 5781
Reputation: 103
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);
Upvotes: 0
Reputation: 41262
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);
}
Upvotes: 3