class ROTP::Base32

def encode(b)

def encode(b)
  data = b.unpack('c*')
  out = String.new
  buffer = data[0]
  idx = 1
  bits_left = 8
  while bits_left > 0 || idx < data.length
    if bits_left < SHIFT
      if idx < data.length
        buffer = buffer << 8
        buffer = buffer | (data[idx] & 255)
        bits_left = bits_left + 8
        idx = idx + 1
      else
        pad = SHIFT - bits_left
        buffer = buffer << pad
        bits_left = bits_left + pad
      end
    end
    val = MASK & (buffer >> (bits_left - SHIFT))
    bits_left = bits_left - SHIFT
    out.concat(CHARS[val])
  end
  return out
end