Skip to content

Instantly share code, notes, and snippets.

@cincodenada
Created September 14, 2013 00:09
Show Gist options
  • Save cincodenada/6557582 to your computer and use it in GitHub Desktop.
Save cincodenada/6557582 to your computer and use it in GitHub Desktop.
Quick binary rotation (rotl/rotr) in Python
def rotl(num, bits):
bit = num & (1 << (bits-1))
num <<= 1
if(bit):
num |= 1
num &= (2**bits-1)
return num
def rotr(num, bits):
num &= (2**bits-1)
bit = num & 1
num >>= 1
if(bit):
num |= (1 << (bits-1))
return num
print rotl(255,8);
print rotr(255,8);
numr=1;
numl=1;
for i in range(0,10):
print "0x%02X (%d)" % (numr,numr)
print "0x%02X (%d)" % (numl,numl)
numr = rotr(numr,8)
numl = rotl(numl,8)
@j4kim
Copy link

j4kim commented Oct 17, 2016

thanks

@racoci
Copy link

racoci commented Sep 29, 2017

You can change 2**x to 1<<x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment