无法从长时间转换浮动

时间:2015-12-02 07:26:09

标签: python floating-point long-integer

我的代码可以从signed字节流转换unsigned值。我能够做到这一点。但是,当我尝试将其转换为float时,它无法简单转换,但会向上舍入到下一个int值。以下是我的代码:

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)

此代码的结果如下:

-23023
<type 'long'>
 -231.0`

但我希望以-230.23格式显示此内容。任何人都可以指导我。

2 个答案:

答案 0 :(得分:2)

将int 100更改为long 100.0。这会奏效。看看最后一行代码:

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)

答案 1 :(得分:0)

您必须使用字节类型和模块&#34; struct&#34;
请尝试以下方法:

import struct    
struct.unpack('f', b'\x00\xff\xa6\x10')

有关转换格式的详细信息,请参阅help(struct)

相关问题