Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a bitwise Not operation in Python?

Tags:

python

In order to test building an Xor operation with more basic building blocks (using Nand, Or, and And in my case) I need to be able to do a Not operation. The built-in not only seems to do this with single bits. If I do:

x = 0b1100 x = not x 

I should get 0b0011 but instead I just get 0b0. What am I doing wrong? Or is Python just missing this basic functionality?

I know that Python has a built-in Xor function but I've been using Python to test things for an HDL project/course where I need to build an Xor gate. I wanted to test this in Python but I can't without an equivalent to a Not gate.

like image 800
Lauren Avatar asked Jul 01 '15 01:07

Lauren


People also ask

How do you perform bitwise NOT operation?

The bitwise NOT operator in C++ is the tilde character ~ . Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.

How do you use bitwise operation in Python?

It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. The left operands value is moved left by the number of bits specified by the right operand. The left operands value is moved right by the number of bits specified by the right operand.

What is << operator in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

What is bitwise XOR Python?

Bitwise XOR (^) operator will take two equal length binary sequence and perform bitwise XOR operation on each pair of bit sequence. XOR operator will return 1, if both bits are different. If bits are same, it will return 0.


2 Answers

The problem with using ~ in Python, is that it works with signed integers. This is also the only way that really makes sense unless you limit yourself to a particular number of bits. It will work ok with bitwise math, but it can make it hard to interpret the intermediate results.

For 4 bit logic, you should just subtract from 0b1111

0b1111 - 0b1100  # == 0b0011 

For 8 bit logic, subtract from 0b11111111 etc.

The general form is

def bit_not(n, numbits=8):     return (1 << numbits) - 1 - n 
like image 173
John La Rooy Avatar answered Sep 24 '22 05:09

John La Rooy


Another way to achieve this, is to assign a mask like this (should be all 1's):

mask = 0b1111 

Then xor it with your number like this:

number = 0b1100 mask = 0b1111 print(bin(number ^ mask)) 

You can refer the xor truth table to know why it works.

like image 43
PKBEST Avatar answered Sep 24 '22 05:09

PKBEST