[Tutor] Binary fractions, recommendations?

Alan Gauld alan.gauld at freenet.co.uk
Fri Aug 4 09:30:59 CEST 2006


> Always found it quite strange that working mathematically with 
> binary
> is so hard in programming languages. Even in Scheme, which will
> happily play with imaginary numbers.

I'm not clear on what you want to do.
You are working mathematically with binary all the time, in fact
that's the reason we get weird results sometimes because its
really binary and not decimal that we are manipulating.
Working in binary is the default behaviour.

>> > Problem is; I can't bitshift on floats, so can't test. Can't 
>> > bitshift
>> > on floats in C either.

Nor even in Assembler.
And that is because a float is really stored in IEEE representation
not in binary. You can bitshift the binary bits but it doesn't do
what you expect in that it doesn't multiply or divide the number
by powers of 2.

But the same is true of decimal numbers represented in
compacted reperesentations, you need to convert to a
normal number first.

> Does anyone know how I could work on a binary
> representation of a float? Any language at all,

Its the same in all languages; you need to convert
the IEE format to a binary format. The simplest way
will likely be a string but you can use two integers too.
Maybe writing a class? - In fact maybe a class exists
if you Google for it...

But why? What will be the advantage in having a
binary format float? And given the huge amount of memory
such a beast vwill consume (the reason we don't store
them like that in the first place) will the advantage
outweigh the cost?

>> In C you can certainly get access to the binary representation of a
>> float as bytes. My C is really rusty but something like
>> float x = 1.3;
>> char* p = &x;

That doesn't give you a binary representation of the
number just access to the bytes of the IEEE representation.
bit shifting that would be pretty pointless IMHO.

>> something similar with the struct module in Python;
> struct.pack() will give you a byte string containing the 
> representation of a float.

If its only the IEEE representation you want to bit shift then
this will be fine. But I'd be really interested in why anyone
would want to do that?

Alan G. 



More information about the Tutor mailing list