1

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?

2
  • 2
    That'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. Commented 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 representation Commented Nov 23, 2010 at 0:15

4 Answers 4

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

}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Problem writing int to binary file in C

Comments

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

1 Comment

Don't you need "%#06x" - without the '#' it just prints 002020.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.