我想将python中的十进制浮点数转换为二进制补码十进制二进制数。例如,1.5的二进制补码十进制2.6(8位)将为0b011000。
是否有可以为我执行此操作的模块?
答案 0 :(得分:1)
你所描述的与十进制没有任何关系。您想将float转换为定点二进制表示。为此,您可以将浮点乘以比例因子,将其转换为整数,并使用Python的内置字符串格式化工具来获取字符串表示:
def float_to_binary(float_):
# Turns the provided floating-point number into a fixed-point
# binary representation with 2 bits for the integer component and
# 6 bits for the fractional component.
temp = float_ * 2**6 # Scale the number up.
temp = int(temp) # Turn it into an integer.
# If you want -1 to display as 0b11000000, include this part:
# if temp < 0:
# temp += 2**8
# The 0 means "pad the number with zeros".
# The 8 means to pad to a width of 8 characters.
# The b means to use binary.
return '{:08b}'.format(temp)
答案 1 :(得分:0)
好吧,我找不到任何东西,所以我写了一些代码并测试了它。应该工作......
def floatToTwosComplementDecimal(intBits,decBits,number):
if decBits == 0:
mx = pow(2,intBits-1) - 1 # maximum number
else:
mx = pow(2,intBits-1) - pow(2,-1*decBits) # maximum number
mn = -1*pow(2,intBits-1) # minimum number
if number > mx:
print "number:" + str(number) + " has been truncated to: " + str(mx)
number = mx
elif number < mn:
print "number:" + str(number) + " has been truncated to: " + str(mn)
number = mn
n = []
m = 0
if number < 0:
n.append(1)
m = -1*pow(2,intBits-1)
else:
n.append(0)
m = 0
for i in reversed(range(intBits-1)):
m1 = m + pow(2,i)
if number < m1:
n.append(0)
else:
n.append(1)
m = m1
for i in range(1,decBits+1):
m1 = m + pow(2,-1*i)
if number < m1:
n.append(0)
else:
n.append(1)
m = m1
return string.join([str(i) for i in n], '')
def twosComplementDecimalToFloat(intBits,decBits,binString):
n = 0.0
if binString[0] == "1":
n = -1*pow(2,intBits-1)
for i in range(intBits-1):
n += int(binString[intBits-1-i])*pow(2,i)
for i in range(1,decBits+1):
n += int(binString[intBits-1+i])*pow(2,-1*i)
return n
答案 2 :(得分:0)
您可以使用 Binary fractions 包。这个包用二进制整数和二进制分数实现 TwosComplement
。您可以将二进制分数字符串转换为二进制补码,反之亦然
示例:
>>> from binary_fractions import TwosComplement
>>> str(TwosComplement(-1.5)) # float --> TwosComplement
'10.1'
>>> str(TwosComplement(1.5)) # float --> TwosComplement
'01.1'
>>> TwosComplement.to_float("11111111111") # TwosComplement --> float
-1.0
>>> TwosComplement.to_float("11111111100") # TwosComplement --> float
-4.0
>>> str(TwosComplement(5)) # int --> TwosComplement
'0101'
要将它与二进制而不是浮点一起使用,您可以在同一个包中使用 Binary
类。
PS:无耻的插件,我是这个包的作者。