在了解了位运算符之后编写实例进行验证,在basis目录下新建文件,命名为bit.py,学习Python位运算符的操作,在PyCharm中输入代码。
operand_a = 5 # 5(DEC) == 0101(BIN)
operand_b = 2 # 2(DEC) == 0010(BIN)
operand_c = 0 # 0(DEC) == 0000(BIN)
按位与运算
operand_c = operand_a & operand_b
print("{} & {} = {}".format(operand_a, operand_b, operand_c))
按位或运算
operand_c = operand_a | operand_b
print("{} | {} = {}".format(operand_a, operand_b, operand_c))
按位取反运算
operand_c = ~operand_a
print("~{} = {}".format(operand_a, operand_c))
左移
operand_c = operand_a << 1
print("{} << 1 = {}".format(operand_a, operand_c))
右移
operand_c = operand_a >> 1
print("{} >> 1 = {}".format(operand_a, operand_c))
按位异或运算
operand_c = operand_a ^ operand_b
print("{} ^ {} = {}".format(operand_a, operand_b, operand_c))