2015-12-02 139 views
1

我的代碼可以將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

修改int 100長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) 
+0

謝謝。就像現在的魅力一樣。 – abhi1610

0

必須使用字節類型和模塊「結構」
嘗試以下操作:

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

而看到的幫助(結構)的更多信息有關轉換格式

+0

並且你nast使用「字節」,而不是「str」 –

相關問題