Playing with the bits of floats

Herman Rubin cik at l.cc.purdue.edu
Tue Jan 17 21:54:13 AEST 1989


In article <1825 at dataio.Data-IO.COM>, bright at Data-IO.COM (Walter Bright) writes:
> In article <MAX.89Jan13163256 at george.lbl.gov> max at george.lbl.gov (Max Rible) writes:
> >I'm trying to do deal with floating point numbers as if they're ints.
< <Things like "if(((3.1 - 3.14) & 0x7FFFFFF) <= 0.1)"--- lousy
< <programming style, I know, but I'm interested in speed, not
< <portability for this application.
> 
> Two ways to do it:
> 	1. Define a union such as:
> 		typedef union
> 		{	double d;
> 			unsigned short u[4];
> 		} dblunion;
> 	   Assign values into d, and do the bit testing with u.
> 	2. Try this:
> 		double d;
> 		d = expression;
> 		if (*(unsigned short *)&d & 0x1234)
> 			...
> I've generally used method 2. I know it violates all notions of
> portability, but it was for very specific hardware! Using method
> 1 sometimes implies passing/returning unions to functions, which
> is inefficiently implemented in a lot of compilers.
> 
> Unless your compiler supports something like (dblunion)(1.2) as
> a 'type paint', I see no way to do this without going through a
> memory location.

This is the sort of lack on the part of languages and compilers which
should not exist.  If the combination (language + compiler) allows
register unions (there are some) and register arrays (I do not know
of any), the following

 	1. Define a union such as:
 		typedef union
 		{	double d;
 			unsigned long u[2];
 		} dblunion;

would work.  The alternative is to use the clumsy assembly language
and even clumsier asm pseudo-function in C.  Even this can give
problems if the register variables in asm lines must be explicitly given,
rather than assigned by the compiler; in that case (which is what I have
to contend with), produce the assembler code with -S and edit it.

I agree that every language should make it easy for the knowledgeable
programmer to do these things, but I am afraid the movement is in the
opposite direction.
-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (Internet, bitnet, UUCP)



More information about the Comp.lang.c mailing list