1 Star 0 Fork 0

杨谨徽/代码托管

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
IEEE754浮点数 3.45 KB
Copy Edit Raw Blame History
杨谨徽 authored 2021-10-16 10:53 +08:00 . add IEEE754浮点数.py
def ConvertFixedIntegerToComplement(fixedInterger) : #浮点数整数部分转换成补码(整数全部为正)
return bin(fixedInterger)[2:]
def ConvertFixedDecimalToComplement(fixedDecimal) : #浮点数小数部分转换成补码
fixedpoint = int(fixedDecimal) / (10.0**len(fixedDecimal))
s = ''
while fixedDecimal != 1.0 and len(s) < 23 : #小数转换成二进制的方法
fixedpoint = fixedpoint * 2.0
s += str(fixedpoint)[0] #这里是取小数乘2所得结果转换成的字符串的第一个索引对应的字符
fixedpoint = fixedpoint if str(fixedpoint)[0] == '0' else fixedpoint - 1.0 #补0或者有1就取1
return s #返回所得字符串s(直到s字符串长度等于23后停止循环)
def ConvertToExponentMarker(number) : #阶码生成(中间部分)
return bin(number + 127)[2:].zfill(8)
def ConvertToFloat(floatingPoint) : #转换成IEEE754标准的数
floatingPointString = str(floatingPoint)
if floatingPointString.find('-') != -1 : #判断符号位
sign = '1'
floatingPointString = floatingPointString[1:]
else :
sign = '0'
l = floatingPointString.split('.') #将整数和小数分离
front = ConvertFixedIntegerToComplement(int(l[0])) #返回整数补码
rear = ConvertFixedDecimalToComplement(l[1]) #返回小数补码
floatingPointString = front + '.' + rear #整合
relativePos = floatingPointString.find('.') - floatingPointString.find('1') #获得字符1的开始位置
if relativePos > 0 : #若小数点在第一个1之后
exponet = ConvertToExponentMarker(relativePos-1) #获得阶码
mantissa = floatingPointString[floatingPointString.find('1')+1 : floatingPointString.find('.')] + floatingPointString[floatingPointString.find('.') + 1 :] # 获得尾数
else :
exponet = ConvertToExponentMarker(relativePos) #获得阶码
mantissa = floatingPointString[floatingPointString.find('1') + 1: ] #获得尾数
mantissa = mantissa[:23] + '0' * (23 - len(mantissa))
floatingPointString = '0b' + sign + exponet + mantissa
return floatingPointString
x = input("请输入一个需要转换的浮点数:")
print(ConvertToFloat(x))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/SHIBATORI/code-hosting.git
git@gitee.com:SHIBATORI/code-hosting.git
SHIBATORI
code-hosting
代码托管
master

Search