我在 python 中創建一個函數,應該將 Decimal(10) 轉換為 Binary(2);由于它應該顯示在小屏幕(計算器)上,我想按字節(8 x 8)拆分輸出字節?,F在,我使用一個我轉換為字符串的列表以水平顯示結果。我試過垂直顯示,每 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 = 0000000100000011代替259 = 0000000100000011
1 回答

胡子哥哥
TA貢獻1825條經驗 獲得超6個贊
您可以切片bin以達到您想要的效果。在打印之前修改您的代碼:
bin = "".join(bin)
bin = "\n".join([bin[i:i+8] for i in range(0, len(bin), 8)])
print(dec2, "=", bin)
這會給你:
259 = 00000001
00000011
這背后的邏輯是什么?
在第一行中,您用于join創建一個包含所有二進制數字的字符串,由一個空格字符分隔。這意味著每8位之間有8個空7個空字符,形成了切片bin時需要考慮的總共15個字符。因此,我使用 16 對每 15 個字符進行切片并得到您想要的結果。
我建議您更改bin = " ".join(bin)為,bin = "".join(bin)以便分隔符為空字符串并每 8 個字符拆分列表,這對您來說是正常且更具可讀性的。隨意問任何其他事情。
添加回答
舉報
0/150
提交
取消