Click to See Complete Forum and Search --> : want to swap byte order


doublec16
10-13-2003, 05:49 PM
I have a binary file that is in the UNIX Sun big endian format (most significant byte first) and I want to use the fread function in a C program to read the numbers in Linux x86, which uses the little endian byte order (least significant byte first). Is there a simple way to do this in a C program? Let's say I have an integer n which I have read with

fread(&n, 4, 1, infile);

This integer is in the exact opposite byte order so that it's the wrong number. Are there a few lines of code I can use to make it the correct number? I think there should be a simple way to do it but I'm not that good with pointers and such. Perhaps there is an environment variable I can set?

Thanks.

PS I have found info about ntoh and hton which convert between the host protocol and network (big endian) protocol, but I'm not sure how to use them. Are they built in C functions, or are they separate?

Stuka
10-13-2003, 05:56 PM
man ntohl

doublec16
10-13-2003, 05:59 PM
You answered my question before I even asked it. Thanks.

doublec16
10-13-2003, 06:10 PM
Just one more thing. Is there equivalent function for floating point and double precision numbers or are they in the same byte order on all platforms?

Thanks.

sploo22
10-13-2003, 06:14 PM
As far as I know, different architectures have completely different floating-point representations. Your best bet is to either avoid them, or use something like GMP to read and write them in a portable format. Or just write them as strings. ;)

bwkaz
10-13-2003, 07:36 PM
Originally posted by sploo22
Or just write them as strings. ;) This has my vote.

sprintf() and sscanf() should view the same number as the same string (barring issues with precision), so you ought to be all right.

Although if you don't have control over the program that wrote the binary file, you're pretty much stuck. You might have luck casting the address of a float (or double) to a char pointer, then filling that, but I highly doubt that it'll work.

(This is why binary file formats are a Very Bad Thing...)

doublec16
10-14-2003, 02:34 AM
Well I wrote a program on the UNIX system to convert the file into ASCII, and I will write another program on the Linux system to convert back to binary, so the program that I want to use will work. The file is rather big and has a lot of numbers and probably the way the original program skips to the correct place is the most efficient method of searching for a particular location in the file.

Thanks for all the advice. I'll keep it in mind next time I run into this difficulty. (Though with FITS format files binary tables work on any platform, and that's mostly what I use.)