Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add one to binary string
#1
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
Reply
#2
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
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [HELP] string into binary ZeroPy 2 2,078 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  hex file to binary or pcap to binary baran01 1 5,706 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  CSV file from Binary to String mr_byte31 2 13,571 Jul-27-2019, 08:46 PM
Last Post: snippsat
  HELP: String of Zero's and One's to binary byte schwasskin 1 3,879 May-19-2019, 07:31 AM
Last Post: heiner55
  binary search string help kietrichards 1 2,217 Mar-08-2019, 12:43 PM
Last Post: stullis
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 2,647 Nov-07-2018, 03:50 AM
Last Post: amygdalas

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020