Photo by Alexander Sinn on Unsplash

Bit Twiddling in Python

--

One thing I love about Python is that I don’t have to do too much C coding anymore. While I still use C to implement cryptography methods that need to run fast, most of the time I just implement my code in Python. If I need the program to run as fast as C, there’s always Golang. And with Python, I can do all the normal bit twiddling methods that I would normally do in C.

Bit shifting

In cryptography, and in many other areas, we often use bit shifting, and where we take all the bits and move them to the right or the left. If the bits that fall of the start or end are fed back into the other side, we define that as a rotate left (ROL) or a rotate right (ROR), otherwise, it is a shift left or a shift right. In Python, the operators for shifting are “<<” (shift left) and “>>” (shift right).

In the following we implement shifts on a given value [here]:

import sys

val1="00110101"

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

print ("Binary form: \t\t",val1)
dec=int(val1,2)

print ("Decimal form: \t\t",dec,"\t",bin(dec)[2:10].rjust(8,'0'))

res=(dec << 1) & 0xff
print ("Shift left (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))

res=(dec << 2) & 0xff

print ("Shift left (2):\t",res,"\t",bin(res)[2:].rjust(8,'0'))

res=(dec >> 1) & 0xff
print ("Shift right (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))

res=(dec >> 2) &…

--

--

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.