Mail Archives: djgpp/2000/02/24/12:20:00
On Thu, 24 Feb 2000, Dieter Buerssner wrote:
> unsigned long l;
> float x;
> fread(&l, sizeof l, 1, fp);
> l = ntohl(l);
> x = *(float *)&l;
>
> My question, is this really more portable? In the libc info for ntohl
> under Portability I read: not ANSI, not POSIX. Is this function
> generally available?
I've seen them on every Unix box I had access to.
> Also, one other problem might arise when
> unsigned long is 64bit (i.e. Alpha, which uses IEEE floating point).
I don't have access to an Alpha to check. Anybody?
> /* Choose MAGIC_FLOAT so, that all four bytes in the IEEE float are
> different. */
> float f = MAGIC_FLOAT;
> /* internel rep. in big endian format */
> unsigned char c[4] = {MAGIC0,MAGIC1,MAGIC2,MAGIC3};
> unsigned char *cp;
> if (CHAR_BIT != 8 || sizeof(float) != 4)
> give up;
> cp = (unsigned char *)&f;
> if (cp[0] == MAGIC0 && cp[1] == MAGIC1
> && cp[2] == MAGIC2 && cp[3] == MAGIC3)
> /* Internal float format is big endian, can use fread without byte
> swapping */
> ...
> else if (cp[0] == MAGIC3 && cp[1] == MAGIC2
> && cp[2] == MAGIC1 && cp[3] == MAGIC0)
> /* Internal float format is little endian, use fread with byte
> swapping */
> ...
> else
> /* Internal format is either some mixed endian, like PDP11 (which
> does not have IEEE floating point), or it is not an IEEE floating
> point format at all, or the compiler is broken and is not able to
> convert MAGIC_FLOAT to binary correctly */
> give up;
> }
>
> Do you think this is portable?
I don't know. In general, I usually advise to stay away of passing FP
numbers between different machines.
- Raw text -