cbp
cbp

Reputation: 25628

How to write two-byte integer as hex into a binary file using C

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

Answers (4)

Henry H
Henry H

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

Mark Wilkins
Mark Wilkins

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

Naveen
Naveen

Reputation: 4688

fprintf(fpout,"%X",input_int);

Upvotes: 0

Related Questions