Mossmyr Mossmyr - 2 months ago 6
C Question

Writing number as raw binary to file

So I'm trying to write the value of a

long
as raw binary to a file with
fwrite()
, here's a test file:

#include<stdio.h>
int main() {
FILE* stream;
stream = fopen("write", "wb");
long number = 0xfff;
fwrite(&number, sizeof(long), 1, stream);
}


When opening the written file in a text editor, this is the output:

ff0f 0000 0000 0000


while I was expecting something like
0000 0000 0000 0fff
.

How do I write the desired result correctly as raw binary?

Answer

There's no problem. You're seeing it as ff0f 0000 0000 0000 cause of the endian of the machine! Try using fread() instead!

Comments