Py42
Py42

Reputation: 201

Incrementing a binary number in python

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!

Upvotes: 3

Views: 19236

Answers (5)

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

Upvotes: 0

NTUI
NTUI

Reputation: 329

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']

Upvotes: 2

Junuxx
Junuxx

Reputation: 14261

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.

Upvotes: 1

wim
wim

Reputation: 362776

>>> 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

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838296

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

Upvotes: 9

Related Questions