code: def convertbits(data, frombits, tobits, pad=True):
      
      acc = 0
      bits = 0
      ret = []
      maxv = (1 << tobits) - 1
      max_acc = (1 << (frombits + tobits - 1)) - 1
      for value in data:
          if value < 0 or (value >> frombits):
              return None
          acc = ((acc << frombits) | value) & max_acc
          bits += frombits
          while bits >= tobits:
              bits -= tobits
              ret.append((acc >> bits) & maxv)
      if pad:
          if bits:
              ret.append((acc << (tobits - bits)) & maxv)
      elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
          return None
      return ret
docs: General power-of-2 base conversion.