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
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.
Output:
1010 + 1
Reverse the strings
0101
+1
Do the addition
0+1 = 1
1+_ = 1
0+_ = 0
1+_ = 1
1101
Reverse the result
1011
If there is a carry
Output:
1010 + 10
Reverse the strings
0101
+01
Do the addition
0+0 = 0
1+1 = 0, carry = 1
0+_+carry = 1
1+_ = 1
0011
Reverse the result
1100
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)