0

I use: Integer.toBinaryString(number); to get binary string.

I want to get the sum of two binary number. how do i do?
example: 0010 + 0011 = 0101!
Thanks! smb help me please!

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by apines
0

Easiest thing would be to do the conversion after the addition, but that's probably not what you're after.

If you have two strings representing binary numbers and you need to add them, you have to
a) grab digits from the right-hand end
b) and add them in standard binary fashion (0+0 =0, 1+0=1, 0+1=1, 1+1=0+carry 1)
c) consing the results into a new string
d) until you run out of digits on one of your strings.

You might find it easier to reverse the strings than to work backwards from string.length(), that's your business, just remember to reverse them back when you're done.

0

Agree with jon.kiparsky, with two things to add: Instead of reversing the string you can zero pad it on the left to make Strings of the same length (String.format should do the trick). Second thing is be careful with the carry - you have to save it throughout the iterations and in each calculation check if it exists or not (it forces more conditions every iteration).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.