Question:
How do I add two binary (negative and/or positive) numbers and get the result in binary aswell.?
2007-09-30 12:53:44 UTC
here is an example of what im thinking. I want to get my program to add two binary string(8-bit 2's complement) number and after show the result like this.

Enter your 1st binary number: 00001111
Enter your 2nd binary number: 00001011

Then I will output the following:
ur 1st binary number is 15
and ur 2nd binary is 11
15 + 11 = 26
26 in binary is 00011010
____________________________

But saying all that, i cant get my program to add or subtract binary string(numbers). Can someone please help me.
Three answers:
Pete
2007-09-30 16:11:09 UTC
To solve this problem, I would convert from binary to decimal first, add the two, and then convert back to binary. My brain thinks in decimal, and I'm sure you have trained your's to as well.



To convert from 2's complement to decimal, just invert the bits and add one. Then loop through the bit string excluding the sign bit and find the decimal value. If the first bit was a one, remeber that its decimal representation is negative.
AnalProgrammer
2007-09-30 13:30:00 UTC
Either get your program to do the sum bit by bit starting at the right.

Or

Convert the strings to decimal and store in an integer field. Add the two numbers and then convert the answer back to binary.



The first option will probably be easier to code.
i_am_the_next_best_one
2007-09-30 23:04:43 UTC
convert into decimal first then add and reconvert into binary


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...