Python学习笔记(2)比特操作、类、文件操作

下面的笔记内容依然来自于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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值