寫個兩個簡單的函式給你參考
# 十進制轉二進制(輸入整數,輸出字串)
def decimalToBinary(number):
output = ""
# 處理32個位元(4 bytes)
for i in range(0, 32):
if number & (1 << i):
output = "1" + output
else:
output = "0" + output
# 把左邊不需要的0刪掉
output = output.lstrip("0")
return "0b" + output
# 二進制轉十進制(輸入0b開頭的字串,輸出數字)
def binaryToDecimal(binary):
if not binary.startswith("0b"):
raise Exception('must start with "0b"')
output = 0;
binaryLen = len(binary)
for i in range(0, binaryLen - 2):
if binary[binaryLen - 1 - i] != "0":
output += 1 << i
return output
測試
print("15 => " + decimalToBinary(15))
print("0b1111 => " + str(binaryToDecimal("0b1111")))
print("321 => " + decimalToBinary(321))
print("0b101000001 => " + str(binaryToDecimal("0b101000001")))
結果
15 => 0b1111
0b1111 => 15
321 => 0b101000001
0b101000001 => 321