<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>
课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾
The Base 2 Number System
Python里,只要开始写上0b
, Python就会知道你之后输入的是二进制。但是即使是二进制输入,二进制计算的默认输出还是十进制。
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()能让输出也是二进制
print bin(6)
print bin(1)
0b110
0b1
int()'s Second Parameter
写2就表示前面的是二进制数字,输出还是十进制
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
【练习:把一个二进制数的tenth digit from the right变成其相反的数字】
a = 0b101
mask = (0b1 << 9) #因为有了一个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:看看一个二进制数的第三位是不是on(即为true/1)】
def third_digit(num):
mask = 0b00100
desired = num & mask
"""
因为mask的第三位是on,所以如果num的第三位是off,
num&mask的第三位就会是off/0/false
mask的数值就变成了0。
否则mask就不会变成0。
"""
if desired > 0:
return True
else:
return False
print third_digit(0b01100)
Output:
True
【例2:把一个二进制数的第三位turn on】
def third_on(num):
mask = 0b100
desired = mask | num
return bin(desired)
print third_on(0b10000)
【例3:翻转(0变成1,1变成0)一个二进制数的所有数字】
num = 0b1011011
mask = 0b1111111
print bin(num^mask)
Output:
0b100100