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!
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!
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.
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).
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.