Python ValueError:在拆分整数和小数时,没有足够的值来解包(预期为2,得到1)
我试图将浮点转换为二进制表示形式。我不明白为什么当我尝试将整数和小数部分分开时,会出现这个错误Python ValueError:在拆分整数和小数时,没有足够的值来解包(预期为2,得到1),python,python-3.x,Python,Python 3.x,我试图将浮点转换为二进制表示形式。我不明白为什么当我尝试将整数和小数部分分开时,会出现这个错误 ValueError:没有足够的值来解包(预期为2,得到1) 这是密码 import decimal from ctypes import * def float_bin(number, places = 32): **whole, dec = str(number).split(".")** whole = int(float(whole)) dec = int (fl
ValueError:没有足够的值来解包(预期为2,得到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_converter中对其执行整数(floor)除法,该除法还返回一个整数,该整数没有小数点可拆分。您的问题在于表5.67e-05中的数字表示。当您将其转换为字符串时,代码将中断 相反,您可以使用以下函数
import decimal
from ctypes import *
def float_bin(number, places = 32):
whole, dec = str(decimal.Decimal(value=str(float(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(".")
dec = int(dec)
res += whole
return res
def decimal_converter(num):
while num > 1:
num /= 10
return num
输出将是
float_bin(0.0000567)
Out[35]: '.10011011101100110011001100110011'
要获得正确的函数输出,您可能需要
import decimal
从ctypes导入*
def float_bin(number):
whole, dec = str(decimal.Decimal(value=str(number))).split(".")
whole = int(float(whole))
dec = int (float(dec))
return bin(whole).lstrip("0b") + "." + bin(dec).lstrip("0b")
def decimal_converter(num):
while num > 1:
num /= 10
return num
float_bin(0.0000567)
Out[52]: '.1000110111'
为了调试这样的问题,您可以在行之间添加一些
print
语句。然后,您可以很容易地看到,dec
之前,x的范围(位置):
为零,因此没有小数点可拆分。我在这个网站上查看了一下,您的代码没有给我正确的值。我确定并更正了您得到的错误,而不是函数输出