Skip to content

Instantly share code, notes, and snippets.

@kennytm
Created May 28, 2010 13:57
Show Gist options
  • Save kennytm/417172 to your computer and use it in GitHub Desktop.
Save kennytm/417172 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.1
import timeit
from itertools import chain
def magic(f): return f
def more_magic(f): return f
@magic
def double_digits_holger8(x):
m = (x * 0x0101010101010101 & 0x8040201008040201) * 0x0102040810204081
return ((m >> 49) & 0x5555) | ((m >> 48) & 0xAAAA)
@more_magic
def double_digits_binmag16(x):
x = (x | x << 8) & 0x00FF00FF;
x = (x | x << 4) & 0x0F0F0F0F;
x = (x | x << 2) & 0x33333333;
x = (x | x << 1) & 0x55555555;
return x | x << 1
def double_digits_mark(x):
return int(bin(x)[2:], 4)*3
def double_digits_max(x):
return int(bin(x)[2:].replace("0","00").replace("1","11"),2)
def double_digits_elegant(x):
X = bin(x)[2:]
return int(''.join([''.join(i) for i in zip(X,X)]), 2)
def double_digits_xavier(x):
X = bin(x)[2:]
return int(''.join(chain(*zip(X, X))), 2)
def double_digits_jim16(x):
y = 0
i = 15
while i >= 0:
if (1 << i) & x:
y |= 3
y <<= 2
i -= 1
return y
def double_digits_peter(n):
result = 0
power = 1
while n > 0:
if n%2==1:
result += 3*power
power *= 4
n //= 2
return result
def double_digits_phimuemue_nolog(x):
numdigits = x.bit_length()
result = 1 << (numdigits*2)
for i in range(numdigits, -1, -1):
mask = 1 << i
if (x & mask > 0):
rmask = 0b11 << (2*i)
result = result | rmask
return result
def double_digits_control(i):
pass
def test(name):
which = globals()[name]
for i in range(256):
which(i)
timeit.main(['-s', 'from __main__ import test;', 'test("double_digits_phimuemue_nolog")'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment