[Tutor] Problems padding a string with 0's while deconcatonating

John Fouhy john at fouhy.net
Tue Dec 6 01:02:24 CET 2005


On 06/12/05, Josh Yagy <JYAGY1 at pride.hofstra.edu> wrote:
> Wow, that code is much more compact, thanks for the help! But as far as the original
> question goes, I think I worded my problem wrong. The output you got with your binary string
> is almost what I Want, but not quite. I need each subset of binary strings to be n bits long (in
> the dummy problem you ran, 4 bits). The last subset is two bits short, but for the sake of the
> cryptosystem, I can't pad it with zeros at the right, I need to pad it to the left. for instance:

Perhaps you could pad the original string!

How much do we pad it by? Well, if n is the word size, we're not
interested in how many complete chunks of n bits there are.  We're
only interested in how many are left over, once we cast out all
complete pieces.  This is equivalent to asking for the remainder,
after dividing the length by n.

eg:

>>> b = '01010011010110101101101'
>>> len(b)
23
>>> len(b)//4    # The // means we want integer division, not real division.
5
>>> len(b)-4*(len(b)//4)
3

So, if we split b into 4 bit pieces, there will be 5 of them, and 3
bits left over.  But there's an easier way to do that calculation ---
the modulo operator:

>>> len(b) % 4
3

That's how many extra bits we have, so we can subtract that from n to
get the number of '0's we need to pad with.

Does that help?

--
John.


More information about the Tutor mailing list