Reputation: 743
I have code which can convert the signed
value from unsigned
byte-stream. I am able to achieve this. But, when i am trying to convert it to float
it can not simply convert but it is rounded up to next int
value. Following is my code:
def byte2int(bstr, width=32):
"""
Convert a byte string into a signed integer value of specified width.
"""
val = sum(ord(b) << 8*n for (n, b) in enumerate(reversed(bstr)))
if val >= (1 << (width - 1)):
val = val - (1 << width)
return val
str1=('\x00\xff\xa6\x10\xff\xff\xa6\x11\xff\xff\xa6\x12\xff\xff\xa6\x13\xff\xff\xa6\x12\xff\xff\xa6\x11\xff\xff\xa6\x10\xff\xff\xa6\x09\xff\xff\xa6\x08')
res=['','','','','','']
k=4
for l in range(0,6):
for i in range (0,4):
res[l]+= str1[i+4*l+k]
Ch1 = (byte2int(res[0]))
print Ch1
print (type(Ch1))
print float(Ch1/100)
Result of this code is following:
-23023
<type 'long'>
-231.0`
But I want to show this in a -230.23
format. Anyone can guide me.
Upvotes: 1
Views: 163
Reputation: 76
You must use byte type and module "struct"
Try the following:
import struct
struct.unpack('f', b'\x00\xff\xa6\x10')
And see help(struct) for more info about converting formats
Upvotes: 0
Reputation: 1803
Change the int 100 to long 100.0. This will work. Look at the last line of code:
def byte2int(bstr, width=32):
"""
Convert a byte string into a signed integer value of specified width.
"""
val = sum(ord(b) << 8*n for (n, b) in enumerate(reversed(bstr)))
if val >= (1 << (width - 1)):
val = val - (1 << width)
return val
str1=('\x00\xff\xa6\x10\xff\xff\xa6\x11\xff\xff\xa6\x12\xff\xff\xa6\x13\xff\xff\xa6\x12\xff\xff\xa6\x11\xff\xff\xa6\x10\xff\xff\xa6\x09\xff\xff\xa6\x08')
res=['','','','','','']
k=4
for l in range(0,6):
for i in range (0,4):
res[l]+= str1[i+4*l+k]
Ch1 = (byte2int(res[0]))
print Ch1
print (type(Ch1))
print float(Ch1/100.0)
Upvotes: 2