NumPy Bitwise Operators

Learn via video courses
Topics Covered

Overview

Computers store all types of data as a stream of binary numbers known as bits. Text, photos, and videos are all composed of ones and zeros. The NumPy bitwise operators in Python allow you to modify individual bits of data at the most micro level.

NumPy Bitwise operators are useful for implementing algorithms like compression, encryption, and error detection. Python frequently uses high-level abstractions to insulate you from the underlying elements. In practice, the overloaded flavors of bitwise operators are more common. However, you will be startled by them while working with them in their natural form!

Introduction

Before proceeding, we will assume that you have successfully installed Python on your PC and are familiar with NumPy arrays.

Let's take a step back and review the binary system, which is necessary for understanding bitwise operators. If you're already acquainted with it, go through to the Bitwise Logical Operators section below.

Numbers can be represented in an unlimited number of ways. People have used various notations since the beginning of time, such as Roman numbers and Egyptian hieroglyphs. The majority of modern civilizations utilize positional notation, which is economical, versatile, and ideally adapted to arithmetic.

Data, on the other hand, is treated by computers as a collection of numbers represented in the base-two numeral system, sometimes known as the binary system. These numerals have only two digits, zero and one.

To illustrate, the binary number 11011000001 is identical to 1729 in the base-10 system.

Now that you have a good understanding of what binary numbers are, it is time to get our hands dirty and study the Bitwise Logical Operations that the NumPy Library provides.

NumPy Bitwise Operators

We all know that NumPy is the mathematical computation model for the majority of data science and machine learning issues, as well as the foundation for many data analytics packages. Along with this, the standard bitwise operations like AND, OR, XOR, and so on have been included and copied into the NumPy bitwise operations, implying that all operations will be done bit by bit. These routines compute output by comparing the binary values of items. NumPy provides six fundamental bitwise operations.

SrNo.Binary OperationDescription
1numpy.bitwise_andPerforms the bit-wise AND operation on two array items
2numpy.bitwise_orPerforms a bit-wise OR operation on two array members
3numpy.bitwise_xorperforms a bit-wise XOR operation on two array members
4numpy.invertThis function computes the bitwise NOT operation between two array items
5numpy.left_shiftThis operator shifts the binary representation of the element's bits to the left
6numpy.right_shiftThis operator shifts the bits of the element's binary representation to the right

This may have been the tip of the iceberg. But don't worry, we'll go over each of them in detail in the blog.

Bit Packing

Let's have a look at some of the NumPy functions for generating binary numbers from decimal numbers and decimal numbers from binary numbers.

1. numpy.binary repr()

In Python, the numpy.binary repr() function creates a binary representation of parameter integers (which can be either negative or positive) as a string. Let's take a quick look at numpy.binary repr().

Syntax :

Example :

Code :

Output :

Note :
If no width is specified for negative values, a minus sign is appended to the front. If width is specified, the two's complement of the integer concerning that width is returned. If you're wondering what width means, it's the length of the returned string if num is positive, or the length of the two's complement, if num is negative, provided width, is at least a sufficient number of bits for num to be represented in the specified form.


2. numpy.packbits()

numpy.packbits() is another method for doing binary operations in NumPy. It is used in an uint8 array to pack the contents of a binary-valued array into bits. By introducing zero bits at the end, the result is padded to full bytes.

Syntax :

Let us thoroughly analyze each argument in the numpy.packbits().

SrNo.Parameter NameParameter Description
1aInput array
2axisThe dimension in which bit-packing is performed. None signifies that the flattened array is packed
3bitorderThe bit order of the input

Example :

Code :

Output :


3. numpy.unpackbits()

numpy.unpackbits() is yet another NumPy binary operations method. It transforms an uint8 array's elements into a binary-valued output array. Each array member represents a bit field that has to be unpacked into a binary-valued output array. The output array has either a 1-D form (if the axis is None) or the same shape as the input array with unpacking along the provided axis. It is the inverse of the numpy.packbits() technique.

Syntax :

Example :

Code :

Output :

It is time to get our hands dirty and study the Bitwise Logical Operations in depth that the NumPy Library provides.

Bitwise AND Operation

The method performs bitwise AND on two array elements. The bitwise function operates on the appropriate bits of the operands' binary representations, i.e. elements. The operation's outcome is determined by the AND truth table.

If both corresponding values are 1, the result is 1, else it is 0. In this case, 1 represents True, and 0 represents False. As a result, the result will be True only if both values are True. Else, it will be False.

Truth table for AND :

abAND( a , b )
000
010
100
111

Syntax :

Before proceeding with the example, let us examine the arguments of the numpy.bitwise_and() function.

SrNo.Parameter NameParameter Description
1x1, x2Input array or integer. Note that, if x1.shape does not equal x2.shape, they must be able to broadcast to a common shape (which becomes the shape of the output)
2outThe place where the result is saved. If no array is given or None is specified, a newly allocated array is returned
3whereThis state is disseminated (spread information) throughout the input. The out array will be set to the ufunc result at locations where the condition is True. The out array will keep its original value elsewhere
4**kwargsIt is possible to pass one or more keyword parameters.

Example :

Code :

Output :

Bitwise OR Operator

This function does a bitwise OR on the array items' binary representation. The operation's outcome is determined by the OR truth table. If one or both of the relevant values are 1, the result is 1, else it is 0.

In this case, 1 represents True, and 0 represents False. As a consequence, the result will be True if one or both of the values are True; otherwise, the result will be False.

Truth Table for OR :

abOR( a , b )
000
011
101
111

Syntax :

Example :

Code :

Output :

XOR Operation

The function XORs has two array members. XOR evaluates two mutually exclusive conditions and notifies you whether one of them has been satisfied or not.

For example, an employee cannot be both a senior and a junior at the same time. An employee, on the other hand, cannot be both a junior and a senior. Making a decision is required. The term XOR stands for "exclusive or" since it performs exclusive disjunction on bit pairs.

The bitwise operation is performed on the relevant bits of the binary representation of the operands, i.e. elements. The operation's outcome is determined by the XOR truth table. If two matching values are the same, the result is 0, otherwise, it is 1.

Truth Table for XOR :

abXOR( a , b )
000
011
101
110

Syntax :

Example :

Code :

Output :

Invert Operation

It computes the bitwise NOT of the items' binary representation. When used with a signed integer, this function yields its 2's complement. The output is determined by the NOT truth table. It inverts the value of the input in the output.

Truth table for NOT :

aNOT( a )
01
10

Syntax :

Example :

Code :

Output :

Left Shift Operation

The numpy.left_shift() shifts the first operand's bits to the left by the number of places provided in its second operand.

It also inserts enough zero bits to cover the gap created on the right edge of the new bit pattern.

A single bit shift to the left by one position doubles its value. For example, following the shift, the bit will represent a four instead of a two. Moving two spaces to the left quadruples the result.

For example, if the integer is 5 and we wish to left shift it by 3 bits, the output will be 5(23)=405*(2^3) = 40. Because bit shifting is a single instruction and is less expensive to calculate than exponent or product, it was formerly a popular optimization approach.

Syntax :

Example :

Code :

Output :

Right Shift Operation

The numpy.right shift() function is similar to the numpy.left_shift() method, except instead of pushing bits to the left, it pushes them to the right by the supplied number of places. The rightmost pieces are usually omitted.

Every one position change to the right reduces the underlying value by half. Moving the same bit two positions to the right yields one-quarter of the original value, and so on.

For example, if the value is 80 and we wish to right shift it three bits, the output will be 80/(23)=1080/(2^3) = 10. A fraction is produced by having an odd number. To get rid of it, the right shift operator automatically floors the output. It's almost identical to a floor division by a power of two.

Syntax :

Example :

Code :

Output :

Kudos! You now have a solid understanding of NumPy Bitwise Operations.

Conclusion

You learned how to :

  • Read and write binary data using the NumPy Library in this session.
  • Individual bits may be controlled in Python with NumPy Bitwise Operators.
  • Understanding Python bitwise operators offers you complete control over binary data in your applications.