delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/02/24/12:20:00

Date: Thu, 24 Feb 2000 18:45:42 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: Dieter Buerssner <buers AT gmx DOT de>
cc: djgpp AT delorie DOT com
Subject: Re: binary to float
In-Reply-To: <200002241539.RAA16262@is.elta.co.il>
Message-ID: <Pine.SUN.3.91.1000224184303.16581A-100000@is>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com
Errors-To: dj-admin AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019