I wrote this small C program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp;
fp = fopen("data.txt","w");
fprintf(fp,"%d",578);
return 0;
}
Then I analyzed data.txt using xxd -b. I was expecting that I will see the 32 bit representation of 578 instead I saw the ASCII representation of 578:
xxd -b data.txt
0000000: 00110101 00110111 00111000 578
Why is that? How do I store the 32 bit representation of 578 (01000010 00000010 00000000 00000000) assuming little endian?
Use fwrite:
uint32_t n = 578;
fwrite(&n, sizeof n, 1, fp);
fprintf is for formatted output, whence the trailing f.
That's the meaning of "Formatted". You used qualifier %d which means "format the given value as its ASCII numeric representation in the execution character set, assuming the value is a signed integer".
If you want to write binary data into a file - don't use formatted output. Use fwrite instead to write raw binary data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With