Bitwise OR?

Clemens Hepper ethrandil at gmx.net
Mon Mar 27 03:27:13 CEST 2006


Okay... pythons build-in methods are quite fast. so is hex().

with about 64 kb memory i can write it with a 16 bit dictionary
where the dictionary generation itself is not yet optimized:

def genBitList(exp):
  next = lambda now: [x+'0' for x in now]+[x+'1' for x in now]
  result = [""]

  for x in range(exp):
    result = next(result)

  return result

_digits = genBitList(16)

def bitstring2(number):
  """lsb------>msb"""
  rlist = list()
  if number >= 0:
    while number:
      rlist.append( _digits[number & 0xFFFF] )
      number >>= 16
    return ''.join(rlist).rstrip('0')
  else:
    while number != -1:
      rlist.append( _digits[number & 0xFFFF] )
      number >>= 16
    return ''.join(rlist).rstrip('1')

this is quite fast and in lots of cases faster than the
hex()-version. however your method (with my inverses formatting) is
very fast, too and without so much memory expense:

_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "a":"1010", "b":"1011",
            "c":"1100", "d":"1101", "e":"1110", "f":"1111",
            "l":"", "-":"", "x":""}

from string import maketrans, translate

_invert = maketrans('01', '10')

def bitstring3( number ):
  if number > 0:
    return ''.join( [_nibbles[d] for d in
      hex(  number ).lower()] ).lstrip( '0' )
  else:
    return translate(''.join( [_nibbles[d] for d in
      hex( ~number ).lower()] ).lstrip( '0' ), _invert)

Benchmark:
  for 0xa:
bitstring2: 0.61802315712
bitstring3: 0.91001200676

  for 0xaaaa:
bitstring2: 0.561501026154
bitstring3: 1.11787199974

  for 0xaaaaaaaaaaaa:
bitstring2: 1.2295820713
bitstring3: 1.61559510231

  for 0xaaaaaaaaaaaaaaaaaaaaaaaa:
bitstring2: 1.90036797523
bitstring3: 2.2683339119

  for -0xaaaaaaaaaaaaaaaaaaaaaaaa:
bitstring2: 2.81339716911
bitstring3: 2.74266886711

mfg
- eth



More information about the Python-list mailing list