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

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
Mayur
  • 13
  • 4
  • `return` is wrongly indented – Cid Apr 16 '19 at 10:27
  • Shouldn't the final output be `(176, 66)`? – DirtyBit Apr 16 '19 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. – Mayur Apr 16 '19 at 10:40

2 Answers2

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)
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
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,)
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75