<a href="http://www.reibang.com/p/54870e9541fc">總目錄</a>
課程頁面:https://www.codecademy.com/
內(nèi)容包含課程筆記和自己的擴(kuò)展折騰
The Base 2 Number System
Python里篙贸,只要開始寫上0b
, Python就會(huì)知道你之后輸入的是二進(jìn)制。但是即使是二進(jìn)制輸入,二進(jìn)制計(jì)算的默認(rèn)輸出還是十進(jìn)制糟红。
print 0b1,
print 0b10,
print 0b110,
print 0b111
print
print 0b1 + 0b11
print 0b11 * 0b11
Output:
1 2 6 7
4
9
The bin() function
bin()能讓輸出也是二進(jìn)制
print bin(6)
print bin(1)
0b110
0b1
int()'s Second Parameter
寫2就表示前面的是二進(jìn)制數(shù)字员魏,輸出還是十進(jìn)制
print int("110", 2)
print int("101", 2)
print int(bin(5),2)
print int("0b11001001", 2)
Output:
6
5
5
201
Left and right shift bitwise operators
# Left Bit Shift (<<)
0b000001 << 2 == 0b000100
0b000101 << 3 == 0b101000
# Right Bit Shift (>>)
0b0010100 >> 3 == 0b000010
0b0000010 >> 2 == 0b000000
【練習(xí):把一個(gè)二進(jìn)制數(shù)的tenth digit from the right變成其相反的數(shù)字】
a = 0b101
mask = (0b1 << 9) #因?yàn)橛辛艘粋€(gè)1了吼肥,只要挪9位
print bin(mask)
print bin(a ^ mask)
Output:
0b1000000000
0b1000000101
The bitwise operators: AND(&), OR(|), XOR(^), NOT(~)
truth table: 1是true录平,0是false
AND(&)
t and t is true: 1 & 1 = 1
t and f is false: 1 & 0 = 0
f and t is false: 0 & 1 = 0
f and f is false: 0 & 0 = 0
OR(|)
t or t is true: 1 | 1 = 1
t or f is true: 1 | 0 = 1
f or t is true: 0 | 1 = 1
f or f is false: 0 | 0 = 0
XOR(^) (exclusive or)
t xor t is false: 1 ^ 1 = 0 # flip out
t xor f is true: 1 ^ 0 = 1
f xor t is true: 0 ^ 1 = 1 # flip out
f xor f is false: 0 ^ 0 = 0
NOT(~)
The bitwise NOT operator (~) just flips all of the bits in a single number. What this actually means to the computer is actually very complicated, so we're not going to get into it. Just know that mathematically, this is equivalent to adding one to the number and then making it negative.
print ~1
print ~2
print ~3
print ~42
print ~123
Output:
-2
-3
-4
-43
-124
Bit mask
A bit mask is just a variable that aids you with bitwise operations. A bit mask can help you turn specific bits on, turn others off, or just collect data from an integer about which bits are on or off.
【例1:看看一個(gè)二進(jìn)制數(shù)的第三位是不是on(即為true/1)】
def third_digit(num):
mask = 0b00100
desired = num & mask
"""
因?yàn)閙ask的第三位是on,所以如果num的第三位是off缀皱,
num&mask的第三位就會(huì)是off/0/false
mask的數(shù)值就變成了0斗这。
否則mask就不會(huì)變成0。
"""
if desired > 0:
return True
else:
return False
print third_digit(0b01100)
Output:
True
【例2:把一個(gè)二進(jìn)制數(shù)的第三位turn on】
def third_on(num):
mask = 0b100
desired = mask | num
return bin(desired)
print third_on(0b10000)
【例3:翻轉(zhuǎn)(0變成1啤斗,1變成0)一個(gè)二進(jìn)制數(shù)的所有數(shù)字】
num = 0b1011011
mask = 0b1111111
print bin(num^mask)
Output:
0b100100