Playing with the bits of floats

Walter Bright bright at Data-IO.COM
Tue Jan 17 05:24:17 AEST 1989


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.



More information about the Comp.lang.c mailing list