ValueError:在拆分整数和小数时,没有足够的值进行解包(应为2,得到1)

2024-10-01 02:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把一个浮点数转换成它的二进制表示形式。我不明白为什么当我试图将整数和小数部分分开时,会出现这个错误

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)

Tags: thetoimportnumberbindefresfloat
2条回答

您在第6行将“dec”定义为一个整数,然后在decimal\u 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'

相关问题 更多 >