python 位运算:按位与、或

背景

回顾一下二进制、十进制、位运算、byte、bit

数据存储最小单位:字节
数据传输单位:位 --> bit 一个位代表一个bit 0或1

转换关系: 1byte = 8bit

八个二进制位可组成一个字节

十进制转二进制

用十进制数字除以二,取余数,倒叙排
5转二进制:101。8bit表示左边补0:0000 0101
image

二进制转十进制

从右往左 <-- 分别乘以2的n次方,然后相加。n从0开始
image

Python中的二进制

bin() 函数将int转化成二进制

>>> bin(5)
'0b101'   # 这里的'0b'标识二进制的意思 后面的101才是计算的结果     请记住这里是字符串格式
>>> 

Python中二进制转换8bit

>>> bin(5).replace('0b','').zfill(8)
'00000101'
>>>

zfill()函数

zfill()函数接受一个数字,代表前面字符串的长度,如果字符串长度小于当前数字,则字符串靠右对齐,前面用0补起长度

Python中的位运算

>>> 5 & 5
5
>>> 5 & 5.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'int' and 'float'
>>> 5&1
1
>>> bin(5) & bin(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'str'
>>> bin(5) & 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'int'
>>> 5.1 & 5.1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
>>>

python 中的与只能用int
记录一下位运算:与 二进制如何计算

     0001 XXXX
           &
     0001 0000
---------------------
     0001 0000

两个都是1的情况结果才能是1,如果有一个是0,那么结果就是0(同真为真)

>>> 5|5
5
>>> 5|1
5
>>> 5|6
7
>>> bin(1) |bin (1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
>>> 

或 二进制运算

A:  0001 0000
        |
B:  0000 0001
--------------
:   0001 0001

其中有一个是1的情况结果是1

左移

>>> 5<<2
20
>>>

箭头朝向哪个方向就是向哪个方向移动

左移的 二进制表示:

A = 0000 0001
A<<4     左移4位  就是将整体往左移动4位,可以理解将'0001' 放到 '0000'位置,后面补0
A<<4 = 0001 0000 

验证python的结果5<<2:

5的二进制:0000 0101
0000 0101
     <<2
------------
0001 0100

0001 0100 转化成十进制:20

image

参考链接

https://www.jianshu.com/p/cfb7df8d3a8b

https://www.jianshu.com/p/e5a8601e7874 byte解析,取高位与低位

https://cloud.tencent.com/developer/article/1588571 16进制

posted @ 2022-09-02 11:46  Tarzen  阅读(724)  评论(0编辑  收藏  举报