0

I am trying to increment a binary sequence in python while maintaining the bit length. So far I am using this piece of code...

'{0:b}'.format(long('0100', 2) + 1)

This will take the binary number, convert it to a long, adds one, then converts it back to a binary number. Eg, 01 -> 10.

However, if I input a number such as '0100', instead of incrementing it to '0101', my code increments it to '101', so it is disregarding the first '0', and just incrementing '100' to '101'.

Any help on how to make my code maintain the bit length will be greatly appreciated. Thanks

3 Answers 3

0

str.format lets you specify the length as a parameter like this

>>> n = '0100'
>>> '{:0{}b}'.format(long(n, 2) + 1, len(n))
'0101'
Sign up to request clarification or add additional context in comments.

Comments

0

That's because 5 is represented as '101' after conversion from int(or long) to binary, so to prefix some 0's before it you've use 0 as filler and pass the width of the initial binary number while formatting.

In [35]: b='0100'

In [36]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
Out[36]: '0101'

In [37]: b='0010000'

In [38]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
Out[38]: '0010001'

2 Comments

That won't work in this case '{0:04b}'.format(long('0000010100', 2) + 1) because you fixed the width to 4, instead of using the length of the input as the OP asked. (Of course maybe the OP should figure it out given what you have....) :)
@RayToal I was about to add that.
0

This is probably best solved using format strings. Get the length of your input, construct a format string from it, and then use it to print the incremented number.

from __future__ import print_function
# Input here, as a string
s = "0101"
# Convert to a number
n = long(s, 2)
# Construct a format string
f = "0{}b".format(len(s))
# Format the incremented number; this is your output
t = format(n + 1, f)
print(t)

To hardcode to four binary places (left-padded by 0) you would use 04b, for five you would use 05b, etc. In the code above we just get the length of the input string.

Oh, and if you input a number like 1111 and add 1 you'll get 10000 since you need an extra bit to represent that. If you want to wrap around to 0000 do t = format(n + 1, f)[-len(s):].

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.