UTILITIES

Return to main page




# von Neumann unbiasing of the bit sequence in the byte array inbyarray.
#
# Besides unbiasing, this function has the inherent effect of decimation
# which could be advantegeous in encryption applications, since it is
# impossible to do the reverse. However, this function has an output
# which is only about 1/4 of the input, i.e. costly.


def vonneumann(inbyarray):
  ones=[0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111]
  val=[0 for i in range(256)]
  nbits=[0 for i in range(256)]
  sshf=6
  smask=0b11 << sshf
  for i in range(256):
    w=0
    nb=0
    shf=sshf
    mask=smask
    for j in range(4):
      u=(i&mask) >> shf
      shf-=2
      mask >>= 2
      if u==0 or u==3:
        continue
      w <<= 1
      nb+=1
      if u==2:
        w|=1   
    val[i]=w
    nbits[i]=nb
# For a byte with value i, von Neumann unbiasing results in nbits[i] bits
# having a binary value val[i].
  liby=len(inbyarray)
  outbyarray=bytearray([])
  g=0
  gbits=0
  for i in range(liby):
    u=inbyarray[i]
    nbitsu=nbits[u]
    if nbitsu > 0:
      g <<= nbitsu
      g|=val[u]
      gbits+=nbitsu
      if gbits >= 8:
        df=gbits-8
        outbyarray.append(g >> df)
        if df > 0:
          g&=ones[df]
        else:
          g=0
        gbits-=8
# Only whole bytes are returned.
  return(outbyarray)



Return to main page