How can I do bit operation on python float value

John Machin sjmachin at lexicon.net
Mon Mar 23 06:32:45 EDT 2009


On Mar 23, 7:44 pm, valpa <valpass... at gmail.com> wrote:
> On 3月23日, 上午3时18分, John Machin <sjmac... at lexicon.net> wrote:
>
>
>
> > On Mar 23, 5:44 pm, valpa <valpass... at gmail.com> wrote:
>
> > > I have a python float 1.2345678. I know that it is stored as a double
> > > in C type. And I know it actually is 1010101010101 -like format. Then
> > > I want to do some bit operation on it. How?
>
> > > Sure, I want a float output when I finish the operation.
>
> > import struct
> > pack it into a str [Python 2.X] using d format
> > unpack it using Q format, gets you a 64-bit unsigned int
> > do "some bit operation" using & | ^ ~ << >> operators
> > pack it into a str using Q format
> > unpack it into a float using d format
>
> > What is "some bit operation"? Perhaps there is already a high-level
> > way of doing some of what you want e.g. in the math module: frexp,
> > ldexp, isnan, isinf, ...
>
> > HTH
> > John
>
> Thanks John!
>
> Yes, I want to do a & operation.
> The pack way is to convert float to/from string,

pack converts various types to a str object,
unpack converts from a str object to various types;
please read the struct manual instead of guessing.

> Is it efficient?

It's relatively efficient, given that what I described takes 4 Python
function calls. In absolute terms, it's a very inefficient way of
doing one & operation on a float. You can try it and see if it is fast
enough for your purpose.

If you tell us what you are trying to do, we might be able to suggest
a better way.

Cheers,
John






More information about the Python-list mailing list