Thursday 15 July 2010

gcc - Binary addition in C, from Arrays -



gcc - Binary addition in C, from Arrays -

i trying add together 2 5bit binary numbers in c. two's complement conversion, need add together 1 original number. see there wealth of code available on net can't function in implementation., getting '00010' execution should '00100'

here

int addbinary(int a[], int b[], int sum[]); int main(){ int i=0; int g =0; int sum[5]; sum[0] =0; sum[1] =0; sum[2] =0; sum[3] =0; sum[4] =0; int b[5]; b[0] =0; b[1] =0; b[2] =0; b[3] =0; b[4] =1; int set[5]; set[0] =0; set[1] =0; set[2] =0; set[3] =1; set[4] =1; addbinary(set,b,sum); } int addbinary(int a[], int b[], int sum[]){ int i, c = 0; for(i = 0; < 5 ; i++){ sum[i] = ((a[i] ^ b[i]) ^ c); // c carry c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c); } sum[i] = c; int z=0; for(z=0; z<5; z++) { printf("%d",sum[z]); } homecoming c; }

you're running add-on msb lsb, carrying in wrong direction.

either alter loop start i=4 , count i down, or alter order of bits in array a[0] lsb , adjust printout loop (which create more sense imo).

c gcc binary c99 twos-complement

No comments:

Post a Comment