我试图把一个浮点数转换成它的二进制表示形式。我不明白为什么当我试图将整数和小数部分分开时,会出现这个错误
ValueError: not enough values to unpack (expected 2, got 1)
这是密码
import decimal
from ctypes import *
def float_bin(number, places = 32):
**whole, dec = str(number).split(".")**
whole = int(float(whole))
dec = int (float(dec))
res = bin(whole).lstrip("0b") + "."
for x in range(places):
whole, dec = str((decimal_converter(dec)) * 2).split(".") ////error here
dec = int(dec)
res += whole
return res
def decimal_converter(num):
while num > 1:
num /= 10
return num
a = float(float_bin(0.0000567))
print ('%32.f', a)
number = cast(pointer(c_float(a)), POINTER(c_int32)).contents.value
bitpos = 0
while number != 0:
bitpos = bitpos + 1 # increment the bit position
number = number >> 1 # shift the whole thing to the right once
if(number >= 1) :
break
print ('%3.f', bitpos)
您在第6行将“dec”定义为一个整数,然后在decimal\u converter中对其执行整数(floor)除法,它还返回一个整数,该整数没有小数点可拆分。你知道吗
您的问题是您的号码在表5.67e-05中的表示方式。当你把它转换成字符串时,你的代码就会中断
相反,您可以使用以下函数
输出将是
为了获得正确的函数输出,您可能需要
从ctypes导入*
相关问题 更多 >
编程相关推荐