Add one to binary string - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Add one to binary string (/thread-38173.html) |
Add one to binary string - uwl - Sep-11-2022 I have a string with the value '0101', it is a binary number. I wish to add one bit to it in order to obtain '0110'. Is someone able to help me accomplish this in my python program. bit_s = '1010' inverse_s = '' #add one bit #two_s = '' two's comp for i in bit_s: if i == '0': inverse_s += '1' else: inverse_s += '0' print("Inversed string is ", inverse_s) #tried + '1' bad output RE: Add one to binary string - deanhystad - Sep-11-2022 Convert it to an int? If this is a homework assignment, and you need to do the addition using the binary string, 1+1 = 0, carry the 1. You don't have a carry in you code. I think it would also be easer working left to right instead of right to left. I would start by reversing the string "1010" to "0101", then I would do the addition, and finally I would reverse the string back. If there is a carry
RE: Add one to binary string - uwl - Sep-11-2022 I mean I do not know how to code logic of each index position of my string has to be added 1 bit or become 0 if it is already 1. You may be right how I need to use a carry. bit_s = '1010' inverse_s = '' two_s = '' int carry = 0 for i in bit_s: if i == '0': inverse_s += '1' else: inverse_s += '0' #logic print(two_s) |