# Thread: Sum binary numbers

1. Member
Join Date
Nov 2009
Posts
12
Rep Power
0

## Sum binary numbers

Hello:

I wrote the following code to sum two binary numbers of the same length:

Java Code:
```public class BinarySum {

public static void main(String[] args) {

int[] a = {0,1,1,1,1,1};
int[] b = {0,1,1,0,1,1};
int[] c = new int[a.length + 1];
int n = a.length + 1;
int m = a.length;
int aux = 0;
int i;

for(i=1 ; i <= m; i++)
{
if(a[m - i] + b[m - i] == 2)
{
c[n-i]= 0 + aux;
aux = 1;
continue;

}

else
{
if(a[m - i] + b[m - i] + aux == 2)
{
c[n-i] = 0;
aux=1;
continue;
}

else
{
c[n-i] = a[a.length - i] + b[b.length - i] + aux;
aux=0;
}

}

}
if(aux == 1)
c[0]=1;
else
c[0]=0;
for(i = 0 ; i < c.length ; i++)
System.out.print(c[i]);

}

}```
I feel it cant be shorter, i mean a way more intelligent to accomplish the task.
Anyone have another idea?

Thanks.
Last edited by Fubarable; 12-13-2009 at 08:42 AM. Reason: code tags added

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
Java Code:
```for ndx = end downto 0
s = a[ndx] + b[ndx] + carry
sum[ndx + 1] = s % 2
carry = s / 2
sum[0] = carry```

or something...
Last edited by pbrockway2; 12-13-2009 at 09:09 AM. Reason: code tags!

3. Member
Join Date
Nov 2009
Posts
12
Rep Power
0
I see thats a very shorter way.
Thanks.

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
You're welcome. It's just a pseudocode description of the ordinary way we do addition (with 10 for 2): "mod" and "div" are actually old friends although they're not usually given names when teaching children to add.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•