Software Engineering

Understanding Bitwise Operators in Python

Understanding Bitwise Operators in Python
Written by admin


There are 6 binary/bitwise operators in Python:

  • Complement/Not (~)
  • And (&)
  • Or (|)
  • XOR (^)
  • Left Shift (<<)
  • Proper Shift (>>)

A implausible python technique to assist us alongside our journey is bin(). The bin operate will return a binary illustration of a base 10 integer we cross to it.

>>> bin(1)
'0b1'

>>> bin(5)
'0b101'

Now let’s discover the 6 bitwise operators by studying a bit about every of them.

Complement/Not (~)

Returns one’s complement of the quantity.

It’s unary and has the impact of ‘flipping’ bits.

Returns the complement of x – the quantity you get by switching every 1 for a 0 and every 0 for a 1. This is identical as -x – 1.

And (&)

Returns 1 if each the bits are 1 else 0.

Operator copies a bit to the end result if it exists in each operands

Does a “bitwise and”. Every little bit of the output is 1 if the corresponding little bit of x AND of y is 1, in any other case it’s 0.

In truth, we are able to additionally use the bitwise & to inform us if an integer is odd and even:

>>> 2 & True
0
>>> 3 & True
1
>>> 11 & True
1
>>> 9 & True
1
>>> 8 & True
0
>>> 80 & True
0
>>> 82 & True
0
>>> 83 & True
1

Or (|)

Returns 1 if both of the bit is 1 else 0.

It copies a bit if it exists in both operand.

Does a “bitwise or”. Every little bit of the output is 0 if the corresponding little bit of x AND of y is 0, in any other case it’s 1.

XOR (^)

Returns 1 if one of many bit is 1 and different is 0 else returns false.

It copies the bit whether it is set in a single operand however not each.

Does a “bitwise unique or”. Every little bit of the output is identical because the corresponding bit in x if that bit in y is 0, and it’s the complement of the bit in x if that bit in y is 1.

Shifting

These operators are used to shift the bits of a quantity left or proper thereby multiplying or dividing the quantity by two respectively. They can be utilized when we have now to multiply or divide a quantity by two.

Left Shift («)

Shifts the bits of the quantity to the left and fills 0 on voids left because of this. Related impact as of multiplying the quantity with some energy of two.

The left operands worth is moved left by the variety of bits specified by the appropriate operand.

Returns x with the bits shifted to the left by y locations (and new bits on the right-hand-side are zeros). This is identical as multiplying x by 2**y.

Proper Shift (»)

Shifts the bits of the quantity to the appropriate and fills 0 on voids left because of this. Related impact as of dividing the quantity with some energy of two.

The left operands worth is moved proper by the variety of bits specified by the appropriate operand.

Returns x with the bits shifted to the appropriate by y locations. This is identical as //’ing x by 2**y.

About the author

admin

Leave a Comment