python位运算符_NumPy按位运算符解析和实例详解

本文概述

Numpy提供以下按位运算符。

SN

Operator

Description

1

bitwise_and

它用于计算相应数组元素之间的按位运算。

2

bitwise_or

它用于计算相应数组元素之间的按位运算。

3

invert

它用于计算按位而不是数组元素的运算。

4

left_shift

它用于将元素的二进制表示形式的位向左移动。

5

right_shift

它用于将元素的二进制表示形式的位向右移。

按位与运算

NumPy提供了bitwise_and()函数, 该函数用于计算两个操作数的bitwise_and运算。

对操作数的二进制表示形式的相应位执行按位与运算。如果操作数中的两个对应位都设置为1, 则仅AND结果中的结果位将设置为1, 否则将设置为0。

例子

import numpy as np

a = 10

b = 12

print("binary representation of a:", bin(a))

print("binary representation of b:", bin(b))

print("Bitwise-and of a and b: ", np.bitwise_and(a, b))

输出

binary representation of a: 0b1010

binary representation of b: 0b1100

Bitwise-and of a and b: 8

和真值表

当且仅当两个位均为1时, 两个位的AND结果的输出为1, 否则为0。

A

B

与(A, B)

0

0

0

0

1

0

1

0

0

1

1

1

按位或运算符

NumPy提供了bitwise_or()函数, 该函数用于计算两个操作数的按位或运算。

对操作数的二进制表示形式的相应位执行按位或运算。如果操作数中的相应位之一设置为1, 则OR结果中的结果位将设置为1;否则, 结果为1。否则它将设置为0。

例子

import numpy as np

a = 50

b = 90

print("binary representation of a:", bin(a))

print("binary representation of b:", bin(b))

print("Bitwise-or of a and b: ", np.bitwise_or(a, b))

输出

binary representation of a: 0b110010

binary representation of b: 0b1011010

Bitwise-or of a and b: 122

或真相表

如果一位中的一位为1, 则两位的或结果的输出为1, 否则为0。

A

B

或(A, B)

0

0

0

0

1

1

1

0

1

1

1

1

反转操作

它用于计算按位而不是给定操作数的运算。如果在函数中传递有符号整数, 则返回2的补码。

考虑以下示例。

例子

import numpy as np

arr = np.array([20], dtype = np.uint8)

print("Binary representation:", np.binary_repr(20, 8))

print(np.invert(arr))

print("Binary representation: ", np.binary_repr(235, 8))

输出

Binary representation: 00010100

[235]

Binary representation: 11101011

它将操作数的二进制表示形式的位向左移动指定位置。从右边追加相等数量的0。考虑以下示例。

例子

import numpy as np

print("left shift of 20 by 3 bits", np.left_shift(20, 3))

print("Binary representation of 20 in 8 bits", np.binary_repr(20, 8))

print("Binary representation of 160 in 8 bits", np.binary_repr(160, 8))

输出

left shift of 20 by 3 bits 160

Binary representation of 20 in 8 bits 00010100

Binary representation of 160 in 8 bits 10100000

右移操作

它将操作数二进制表示形式的位向右移动指定位置。从左边追加相等数量的0。考虑以下示例。

例子

import numpy as np

print("left shift of 20 by 3 bits", np.right_shift(20, 3))

print("Binary representation of 20 in 8 bits", np.binary_repr(20, 8))

print("Binary representation of 160 in 8 bits", np.binary_repr(160, 8))

输出

left shift of 20 by 3 bits 2

Binary representation of 20 in 8 bits 00010100

Binary representation of 160 in 8 bits 10100000

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值