下面的笔记内容依然来自于codecademy
比特操作
注意一: 适用范围 Note that you can only do bitwise operations on an integer. Trying to do them on strings or floats will result in nonsensical output!
print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT
比特操作 - 打印二进制
print 0b1, #1
print 0b10, #2
print 0b11, #3
print 0b100, #4
print 0b101, #5
print 0b110, #6
print 0b111 #7
print "******"
print 0b1 + 0b11
print 0b11 * 0b11
比特操作 - 将十进制的number转换为二进制的str
注意(1) 可以将十进制转换为二进制bin()、八进制oct()、十六进制hex(),转换后为str型,不再是number
print bin(1)
for i in range(2,6):
print bin(i)
比特操作 - 将二进制的str转换为十进制的number
print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)
比特操作-左移右移(slide to the left, slide to the right)
1 Note that using the & operator can only result in a number that is less than or equal to the smaller of the two values
2 Note that the bitwise | operator can only create results that are greater than or equal to the larger of the two integer inputs.
shift_right = 0b1100
shift_left = 0b1
# Your code here!
shift_right=shift_right >>2
shift_left=shift_left<<2
print bin(shift_right)
print bin(shift_left)
比特操作-NOT
1 Just know that mathematically, this is equivalent to adding one to the number and then making it negative.
2 just flips all of the bits in a single number
print ~1
print ~2
print ~3
print ~42
print ~123
比特操作-Mask-例1
A bit mask is just a variable that aids you with bitwis