我在 python 中创建一个函数,应该将 Decimal(10) 转换为 Binary(2);
由于它应该显示在小屏幕(计算器)上,我想按字节(8 x 8)拆分输出字节。现在,我使用一个我转换为字符串的列表以水平显示结果。
我试过垂直显示,每 8 个字符暂停一次。(它有效,但我想要一个水平显示);
还尝试显示列表并每 8 个字符清除一次,但没有成功。
def dectobin(dec):
maxbin = 7
maxdec = 2**maxbin
dec2 = dec
bin = []
#Define default maximum values
#for the Binary and Decimal numbers
#starting from one Byte
dec = abs(dec)
#Negative value to positive value
while dec > maxdec:
maxbin = maxbin+8
maxdec = 2**maxbin
#Define the actual maximum values
#for the Binary and Decimal numbers
#incremented in Bytes
while maxbin != -1:
#Set the loop to stop at final bit
b = dec-2**maxbin
#Saving dec into another var
#in order to do the tests
if b < 0:
bin.append("0")
#If dec < maxbin value, it's a 0
else:
bin.append("1")
#If dec > maxbin value, it's a 1
dec=b
maxbin = maxbin-1
#Decrease the bit
bin = " ".join(bin)
print(dec2, "=", bin)
例如,如果我输入“259”,我想要
259 = 00000001
00000011
代替
259 = 0000000100000011
冉冉说
胡子哥哥
随时随地看视频慕课网APP
相关分类