3

I wonder, how can I increment a string representing a binary number, all the way up to another binary number? (for use in a while loop, for example).

For example I start with "0000" and after 15 incs, I should reach "1111" (in other words: "0000", "0001", "0010", ..., "1111"). At first this problem seemed really simple, but the only solutions I could come up with were quite ridiculous (not pythonic, some might say). Does anyone have an advice?

Thanks in advance!

3
  • 5
    Is there a reason why you want to start out with strings, and not with integers that you convert to strings for display purposes? Commented May 20, 2012 at 11:34
  • 2
    @Mark Byers I have no plausible explanation for that. Facepalm. Commented May 20, 2012 at 11:35
  • 1
    [format(n, '04b') for n in range(16)] Commented May 20, 2012 at 11:50

5 Answers 5

10

To do what you literally asked for you should convert to an integer, add one, then change back to binary.

x = to_binary(int(x, 2) + 1)

You may find the bin built-in method useful in implementing to_binary, though you will need to modify its output slightly to match your desired result.

However it would be better if possible to not convert back and forth: just store an integer and convert it to binary when you need to display it.

On reading your question carefully though, it seems that all you want to do is to generate the strings '0000', '0001', '0010', etc. If this is correct, then I suggest using itertools.product.

Example:

import itertools
for x in map(''.join, itertools.product('01', repeat=4)):
    print x

0000
0001
0010
...

See it working online: ideone

Sign up to request clarification or add additional context in comments.

1 Comment

What an ingenious solution! I would've never come up with that. I'm repeatedly amazed at what Python has to offer. Thank you =]
3
>>> def increment_binary_string(s):
...   return '{:04b}'.format(1 + int(s, 2))
... 
>>> x = '0000'
>>> for _ in xrange(15):
...   print x
...   x = increment_binary_string(x)
... 
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110

4 Comments

This is similar to a solution I tried, the problem is that it returns "1" instead of "0001" (I combined that with a padding function that just pads the result with leading zeros).
Oh, ok, for leading zeros you can use str.format (see edit)
By the way, I agree with Mark about the real answer, which is just work with integer, and convert for display when necessary
Thanks, I wasn't very familiar with str.format up until now =]
2

This is simple to do with bin() and zfill().

>>> for x in range(16):
...     print bin(x)[2:].zfill(4)
... 
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

Or you can put the values in a list with a comprehension:

>>> [bin(x)[2:].zfill(4) for x in range(16)]
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

Comments

1

Short and simple with the default function bin():

>>> for i in range(15):
...     print bin(i)
...
0b1
0b10
0b11
0b100
0b101
0b110
0b111
0b1000
0b1001
0b1010
0b1011
0b1100
0b1101
0b1110
0b1111

If you don't like that they start with the 0b prefix, you can use print str(bin(i))[2:] instead.

Comments

0

If you want use only strings:

def increment(l):
    if len(l) == 0:
        return l

    if l[-1] == '0':
        l = l[:-1] + '1'
    else:
        l = increment(l[:-1]) + '0'

    return l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.