Photo by Alexander Sinn on Unsplash

Bitwise Operations In Python

--

I love using Python, and it feels like it was written by technical people for technical people. When dealing with numbers, it just allows you to get right down into bit level. So let’s look at some of the bitwise operations.

Bit operations

In Python, we either have logical operations, such as && for AND and || for OR, or we have bitwise operations, such as & for AND and | for OR. Thus for a bitwise OR operation we have:

A B Z
0 0 0
0 1 1
1 0 1
1 1 1

and for AND:

A B Z
0 0 0
0 1 0
1 0 0
1 1 1

We can then add in a NOT operation, and which will invert a given bit, and an X-OR operation:

A B Z
0 0 0
0 1 1
1 0 1
1 1 0

If we compile a NOT and an OR, we get NOR:

A B Z
0 0 1
0 1 0
1 0 0
1 1 0

And this gives us our basic logic gates, and where we can implement any function we want. The following is the Python code and which operates on eight bit values [here]:

import sys

val1="00110101"
val2="00110111"

if (len(sys.argv)>1):
val1=sys.argv[1]


if (len(sys.argv)>2):
val2=sys.argv[2]

def nor(p, q):
return ~ (p | q) & 0xff;

def nand(p, q):
return ~(p & q) & 0xff;

dec1=int(val1,2)
dec2=int(val2,2)

print ("Decimal…

--

--

Prof Bill Buchanan OBE FRSE
ASecuritySite: When Bob Met Alice

Professor of Cryptography. Serial innovator. Believer in fairness, justice & freedom. Based in Edinburgh. Old World Breaker. New World Creator. Building trust.