不能将十进制写到二进制,反之亦然,它可以处理正负数。
这个十进制到二进制转换器工作精细的
# decimal to binary
def to2sCompStr(num):
bitWidth = 8
num &= (2 << bitWidth-1)-1
formatStr = '{:0'+str(bitWidth)+'b}'
ret = formatStr.format(int(num))
return ret
print(to2sCompStr(-100))
#output 10011100
# Binary To decimal
binary = 10011100
print(int(binary, 2))
# output 156, not -100二进制到十进制只在正数上工作,而不是负的。
发布于 2022-10-24 18:05:51
为了转换二进制字符串,对基参数设置为2的int函数的调用不识别两个补码表示法中的输入。它不能假设输入字符串的最左边的“位”(实际上是一个字符'0‘或'1')是符号位。然而,它确实能识别出一个主要的“-”字符。
因此,在调用to2sCompStr之前,您的int()需要否定负数,然后用‘-’作为结果的前缀:
# decimal to binary
def to2sCompStr(num):
bitWidth = 8
if num < 0:
negative = True
num = -num
else:
negative = False
num &= (2 << bitWidth-1)-1
formatStr = '-{:0'+str(bitWidth)+'b}' if negative else '{:0'+str(bitWidth)+'b}'
return formatStr.format(int(num))
binary = to2sCompStr(-100)
print(binary)
#output -01100100
print(int(binary, 2))
# output -100指纹:
-01100100
-100另一种方法是不使用int内置函数:
BITWIDTH = 8
MAX_POSITIVE_NUM = 2 ** (BITWIDTH - 1) - 1
MIN_NEGATIVE_NUM = -(2 ** (BITWIDTH - 1))
# decimal to binary:
def to2sCompStr(num):
if not (MIN_NEGATIVE_NUM <= num <= MAX_POSITIVE_NUM):
raise ValueError(f'Invalid input: {num}')
num &= (2 << BITWIDTH-1)-1
formatStr = '{:0'+str(BITWIDTH)+'b}'
return formatStr.format(int(num))
# binary to decimal:
def strTo2Int(num):
n = int(num, 2)
return n if num[0] == '0' else -(2**len(num) - n)
for n in (0, 1, -1, 100, -100):
base2 = to2sCompStr(n)
base10 = strTo2Int(base2)
print(n, base2, base10)指纹:
0 00000000 0
1 00000001 1
-1 11111111 -1
100 01100100 100
-100 10011100 -100https://stackoverflow.com/questions/74181325
复制相似问题