python float字节数_float型的数在内存中的表示 附:python3解析函数 | 学步园
32為操作系統(tǒng)中float型的數(shù)是4個字節(jié)(32位),小數(shù)0.002122二進(jìn)制格式如下:
00111011000010110001000101000001
左起第1位:是整個數(shù)的符號位,0正 1
負(fù)左起第2-9位:是指數(shù)的倒數(shù)
左起10-32位:是科學(xué)計(jì)數(shù)法系數(shù)的小數(shù)部分 (二進(jìn)制表示)
下面是我寫的一個解析float內(nèi)存結(jié)構(gòu)的函數(shù),python3寫的
##文件名:decimal.py
#輸入32個01組成的二進(jìn)制字符串
def decimals( dat):
lendat = len(dat)
if lendat != 32:
print('字符串長度不是32')
return 0
for c in dat:
if (c != '0') and (c != '1'):
print('輸入的字符串含有不合法的字符')
return 0
#dattemp = dat[24:32]+dat[16:24]+dat[8:16]+dat[0:8] #寫到硬盤上的浮點(diǎn)數(shù)要調(diào)整順序 順序顛倒
dattemp = dat
print('dattemp:',dattemp)
sigbit = dattemp[0]???????? #符號位
expsigbit = dattemp[1]????? #指數(shù)符號位
exponent = dattemp[2:9]???? #指數(shù)
mantissa = dattemp[9:32]??? #尾數(shù)
print(sigbit,expsigbit,exponent,mantissa)
print('總長度:',(len(sigbit)+len(expsigbit)+len(exponent)+len(mantissa)))
iexp = 0??????????????? #指數(shù)的十進(jìn)制
print('符號位sigbit:',sigbit)
print('指數(shù)符號位expsigbit:',expsigbit)
print('指數(shù)exponent:',exponent)
print('尾數(shù)mantissa:',mantissa)
ipos = 0??????????????? #游標(biāo) 標(biāo)記'1'的位置
#[expsigbit+dattemp] 就是原來原小數(shù)(二進(jìn)制數(shù))轉(zhuǎn)換成科學(xué)計(jì)數(shù)法后 (樣子像這樣:1.1001101*2^n) 那個2上面的指數(shù)n
temp = exponent[::-1]
for c in temp:
if (c == '1') ^ (expsigbit == '0'): #右移時算'0'的個數(shù) 左移時算'1'的個數(shù) 不移不算
iexp += 2**ipos
#print('當(dāng)iops=',ipos,'時,iexp=',iexp,' c:',c,'expsigbit:',expsigbit)
ipos += 1
else:
if expsigbit == '1':#如果是左移 位數(shù)值要加1
iexp += 1
iexp *= -1
#print("得到標(biāo)志:",iexp)
iexp *= -1 #這里乘以-1是為了下面的好算,這就是指數(shù)了
#print("指數(shù)為",iexp)
decimalpart = 0.0?????? #科學(xué)計(jì)數(shù)法的小數(shù)部分
ipos = 0??????????????? #游標(biāo) 標(biāo)記'1'的位置
for c in mantissa:
ipos += 1
if c=='1':
decimalpart += 2**-ipos
#print('decimalpart=',decimalpart,'/t2^-',ipos,'=',2**-ipos)
intpart = 1???????????? #整數(shù)部分 因?yàn)?進(jìn)制的數(shù)科學(xué)計(jì)數(shù)法 整數(shù)部分只能是1
#print('decimalpart:',decimalpart)
if sigbit == '0':
flt = (intpart + decimalpart)*2**(iexp)
else:
flt = (-1)*(intpart + decimalpart)*2**(iexp)
return flt
################################
#文件名:main.py
#調(diào)用方法如下:
from decimal import *
s='00111011000010110001000101000001'
print('原始字符串為:',s)
print('解析結(jié)果為:',decimals(s))
解析結(jié)果為: 0.00212200009264
小數(shù)的結(jié)果不完全等于原來的小數(shù) 因?yàn)楦↑c(diǎn)數(shù)有誤差 (尾數(shù)段不夠長,double的長一些所以更精確)
總結(jié)
以上是生活随笔為你收集整理的python float字节数_float型的数在内存中的表示 附:python3解析函数 | 学步园的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何查看QQ空间消息
- 下一篇: websocket python爬虫_p