Converting float numbers to binary

3

I need to convert a float value to binary. This value can be from 0 to 99.99.

I saw that if the value is an int and between 0 to 255 I just have to do

n = [255]
num = byte(n)

How is not possible directly convert a float to binary (I think), my first step was multiply my float number *100 and have an integer from 0 to 9999.

Now I need 4 bytes to represent the number.

It is possible do something like this arduino code (below)?

n = 9999
byte = pl[4];

pl[0] = (byte) ((n & 0xFF000000) >> 24 );
pl[1] = (byte) ((n & 0x00FF0000) >> 16 );
pl[2] = (byte) ((n & 0x0000FF00) >> 8 );
pl[3] = (byte) ((n & 0X000000FF));

Basically I'm applying a mask, but I don't know how to do it with python because I'm a noob. :/

MORE INFO:

The objective is to reduce the length of my result to send this with a wireless protocol. That's why I'm converting it to byte.

Thank you very much

python
python-3.x
asked on Stack Overflow Dec 7, 2019 by Lleims • edited Dec 7, 2019 by Lleims

3 Answers

2

One equivalent would be

x=2049
p0 = (x>>24)&255
p1 = (x>>16)&255
p2 = (x>>8)&255
p3 = x&255
answered on Stack Overflow Dec 7, 2019 by jeremy_rutman
1

Yes you can do exactly the same thing in python.

This would be the literal translation of your code.

n = int(floatnumber * 100 + 0.5)
bytes_to_write = bytes([(n>>24)&255, (n>>16)&255, (n>>8) & 255, n & 255])

However you could also use the struct module ( https://docs.python.org/3.6/library/struct.html ) and ( https://docs.python.org/3.6/library/struct.html#format-characters ) for the format characters:

import struct
n = int(floatnumber * 100 + 0.5)
bytes_to_write = struct.pack(">l", n)

storing the int as big endian byte sequence

For creating only two bytes use

n = int(floatnumber * 100 + 0.5)
bytes_to_write = bytes([(n>>8) & 255, n & 255])

or

import struct
n = int(floatnumber * 100 + 0.5)
bytes_to_write = struct.pack(">H", n)
answered on Stack Overflow Dec 7, 2019 by gelonida • edited Dec 8, 2019 by gelonida
1

As per your comments You need this:

number = float(input("Enter any number:"))
decimal = int(str(number).split(".")[0])
print(decimal)
mantissa= int(str(number).split(".")[1])
print(mantissa)
if mantissa != 0:
    pass
else:
    mantissa = 0
int_num = decimal*(10**(len(str(mantissa))))+mantissa

You'll get the integer value of that number without decimal point. Now you can convert that into binary directly.

answered on Stack Overflow Dec 7, 2019 by theashwanisingla

User contributions licensed under CC BY-SA 3.0