Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!amdcad!ames!ucbcad!ucbvax!hplabs!pyramid!epimass!jbuck From: jbuck@epimass.EPI.COM (Joe Buck) Newsgroups: comp.unix.wizards Subject: Re: casting to float without converting to float? Message-ID: <1815@epimass.EPI.COM> Date: 8 Jan 88 17:52:42 GMT References: <11171@brl-adm.ARPA> Reply-To: jbuck@epimass.EPI.COM (Joe Buck) Organization: Entropic Processing, Inc., Cupertino, CA Lines: 32 In article <11171@brl-adm.ARPA> weiser.pa@Xerox.COM writes: >I have the following problem: I have a value which I happen to know >has the proper bits to represent a floating point number (either 32 >or 64). However, it is of type int. I would now like to tell the C >compiler to treat this thing as a float. How can I do it without >taking the address of the thing (which may not have an address >because it is in a register or is an expression) or using a >subroutine call (for which I do not wish to pay the cost)? Casts are conversions. Because of the way they work with pointers on byte-addressible machines, many beginners seem to think that (type)x means to treat the bit pattern in x as if it were of type "type", but it most emphatically doesn't. But, we have unions to deal with this problem. If you have a machine in which both ints and floats have the same length, the following will work. union { int i_format; float f_format; } fubar; #define CONVERT(x) (fubar.i_format = (x), fubar.f_format) This is absolutely horrible and nonportable (it's not predictable if the lengths of ints and floats isn't the same), but it will work for your specific problem. -- - Joe Buck {uunet,ucbvax,sun,decwrl,}!epimass.epi.com!jbuck Old internet mailers: jbuck%epimass.epi.com@uunet.uu.net Argue for your limitations and you get to keep them. -- Richard Bach