S. Takano
S. Takano

Reputation: 313

How read particular bit position of floating number?

I want to read particular position of floating number such as x[16:3] (4th-bit to 17th-bit). Case of C-language is is simple like this

bits = x & ((2**L - 1) << M);

Case of Python, '&' of mask operation is not allowed for floating point numbers. Then how to do it on the Python?

Upvotes: 1

Views: 59

Answers (1)

Lepakk
Lepakk

Reputation: 449

I'm not sure, if I understand you correctly, but this would be my solution:

import struct

def float_to_bin(num):
    return format(struct.unpack('!I', struct.pack('!f', num))[0], '032b')

x=16.4637159674589415472835945

string=str(x)
bitx=float_to_bin(x)

part_of_string=string[4:17]
part_of_bitx=bitx[4:17]

I copied the float_to_bin function once from somewhere else (probably somewhere from Stackoverflow) to make the float a binary number. That function already makes the binary number a string, so then you can just use the usual indexing. If you want to read the particular position of the float number, you can just make that number a string and then use the indexing.

I hope, I got your question right. Best, lepakk

Upvotes: 1

Related Questions