1

I have binary string which is "00000000000000001011000001000010". I want to convert this string to byte array and from that byte array,I want to obtain corresponding float value. How it can be done in python?

I tried doing it using struct.unpack().

def bitstring_to_bytes(s):
    v = int(s, 2)
    b = bytearray()
    while v:
        b.append(v & 0xff)
        v >>= 8
        return bytes(b[::-1])

>>> s="00000000000000001011000001000010"
>>> print(bitstring_to_bytes(s))
>>> B
>>> struct.unpack('>f',B)

Also guide me on getting float value from byte array. Finally, we should obtain float value=88.0

3
  • return is wrongly indented Commented Apr 16, 2019 at 10:27
  • Shouldn't the final output be (176, 66)? Commented Apr 16, 2019 at 10:36
  • Yes you are right. Actually, I am trying to retrieve encoded data from MODBUS transmitter. Consider transmitter is sending data=88. Their encoding method is first they convert value to string,from string to float and from float to byte array(4 elements or 32 bits). Anyhow I came to know that transmitted value is 88 and bit stream after byte array is as pasted. I am trying to obtain results using reverse processing. Commented Apr 16, 2019 at 10:40

2 Answers 2

1

You can convert to an int and use the to_bytes method:

s="00000000000000001011000001000010"

def bitstring_to_bytes(s):
    return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

print(bitstring_to_bytes(s))

>>>b'\x00\x00\xb0B'

And to get a float:

import struct

struct.unpack('f', bitstring_to_bytes(s))

>>>(88.0,)
Sign up to request clarification or add additional context in comments.

2 Comments

Now please help me in getting float value from this byte array.
It's already in the answer.
1

From the docs:

Using unsigned char type:

import struct

def bitstring_to_bytes(s):
     v = int(s, 2)
     b = bytearray()
     while v:
         b.append(v & 0xff)
         v >>= 8
     return bytes(b[::-1])

s = "00000000000000001011000001000010"
r = bitstring_to_bytes(s)
print(struct.unpack('2B', r))

OUTPUT:

(176, 66)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.