public
Created

  • Download Gist
stackoverflow_2929404.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#!/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")'])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.