Re: How to make binary data portable?



PengYu.UT@xxxxxxxxx wrote:
> Hi,
>
> I write the content of a in file "data" (in Sun Machine). Then I read
> "data" in both SunOS and linux. But the result is different. Do you
> know how to make it binary data portable.
>
> Best wishes,
> Peng

If you are consistent about the following three things you should be OK
on the vast majority of platforms:
1) type (float, signed integer, unsigned integer)
2) size
3) endianness

For example if you always represent some value in your file as a 32 bit
big endian unsigned integer you will have no problems as long as you
are consistent about this. (Always read and write the value as a 32
bit big endian unsigned integer. It would be good programming practice
to have one module which handles this.)

The C99 header stdint.h provides definitions of signed and unsigned
integers with specific sizes/widths.

Floating point numbers can be a headache especially if your data is
moving across machines that don't use ieee floats. If you seach the
internet you will probably be able to find C code which converts other
floating point representations to the ieee representation.

To ensure consistent endianness byte swapping macros will probably come
in handy. glib and other libraries provide these kind of macros
(http://developer.gnome.org/doc/API/glib/), also see hton() and
friends.

-Charlie

>
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main(int argc, char *argv[]){
>
> int a = 100;
> int b;
>
> FILE *fp;
> /* fp = fopen("data", "w");
> fwrite(&a, sizeof(int), 1, fp);
> fclose(fp);
> */
>
> fp = fopen("data", "r");
> fread(&b, sizeof(int), 1, fp);
> fclose(fp);
>
> printf("b = %x\n", *((unsigned int*)&b));
>
>
> return 0;
> }

.