Date: Thu, 24 Feb 2000 18:45:42 +0200 (IST) From: Eli Zaretskii X-Sender: eliz AT is To: Dieter Buerssner cc: djgpp AT delorie DOT com Subject: Re: binary to float In-Reply-To: <200002241539.RAA16262@is.elta.co.il> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII 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 Precedence: bulk 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.