1 整數(shù)绩卤,由十進(jìn)制轉(zhuǎn)二進(jìn)制
十進(jìn)制整數(shù) 123 可以理解為 1x102 + 2x101 + 3x100叁鉴。
同樣的土涝,二進(jìn)制整數(shù) 0b1101 也可以理解為 1x23 + 1x22 + 0x21 + 1x20。(十進(jìn)制 8 + 4 +1 = 13)
在計(jì)算機(jī)內(nèi)部幌墓,所有數(shù)字都是由二進(jìn)制表示的但壮。
以 13 為例,我們看下由十進(jìn)制向二進(jìn)制轉(zhuǎn)換的方法:
13 / 2 = 6 余 1
6 / 2 = 3 余 0
3 / 2 = 1 余 1
1 / 2 = 0 余 1
除2的余數(shù)常侣,相當(dāng)于右移后拋棄的那一位蜡饵。
最先拋棄的寫在最右邊,
故胳施,13 = 0b1101
下面溯祸,寫一段 Python 代碼來(lái)實(shí)現(xiàn)十進(jìn)制到二進(jìn)制的轉(zhuǎn)換。
num = 13
result = ''
while num > 0:
result = str(num%2) + result
num = num // 2
print("Decimal number 13 is binary", result)
運(yùn)行結(jié)果:
Decimal number 13 is binary 1101
接下來(lái)的小數(shù)轉(zhuǎn)換會(huì)重用這段代碼舞肆。
2 小數(shù)焦辅,由十進(jìn)制轉(zhuǎn)二進(jìn)制
十進(jìn)制整數(shù) 0.123 可以理解為 1x10-1 + 2x10-2 + 3x10-3。
同樣的椿胯,二進(jìn)制整數(shù) 0b0.011 也可以理解為 0x2-1 + 1x2-2 + 1x2-3筷登。(十進(jìn)制 0.25 + 0.125 = 0.375)
小數(shù)十進(jìn)制轉(zhuǎn)二進(jìn)制的思路是:如果這個(gè)小數(shù)乘以2n后可以變成一個(gè)整數(shù),那么這個(gè)整數(shù)先轉(zhuǎn)二進(jìn)制哩盲,然后除以2n前方。除2n等于右移n位。
例如:
0.375 * 23 = 3廉油,
0b11右移3位镣丑,
故 0.375 = 0b0.011
下面寫段 Python 代碼來(lái)實(shí)現(xiàn)這個(gè)轉(zhuǎn)換功能。
x = float(input("Enter a decimal number between 0 and 1:"))
p = 0
while x*(2**p)-int(x*(2**p)) != 0:
print("p=", p, " Remainder =", x*(2**p)-int(x*(2**p)))
p += 1
num = int(x*(2**p))
result = ""
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num // 2
for i in range(p - len(result)):
result = '0' + result
result = '.' + result
print("The binary representationof the decimal", x, "is", result)
運(yùn)行結(jié)果:
Enter a decimal number between 0 and 1:.375
p= 0 Remainder = 0.375
p= 1 Remainder = 0.75
p= 2 Remainder = 0.5
The binary representationof the decimal 0.375 is .011
參考文獻(xiàn)
Introduction to Computer Science and Programming Using Python