 What does this code do?

#include<stdio.h>

typedef char bit;
bit carry = 0;
bit halfadd( bit A, bit B )
{
carry = A & B;
return A ^ B;
}
bit fulladd( bit A, bit B )
{
bit xor = A ^ B;
bit ret = carry ^ xor;
carry = (carry & xor) | (A & B);
return ret;
}

void fillNum( int num, bit *array )
{
int i;
for( i = 0; i < 32; ++ i ){
array[i] = ( num >> i ) & 1;
}
}

int main()
{
bit num1 = {0}, num2 = {0};
int A = 220, B = 224;
fillNum( A, num1 );
fillNum( B, num2 );

int r = 0;
bit tmp = halfadd( num1, num2 );
putchar( tmp ? '1' : '0' );
r = tmp;
int i;
for( i = 1; i < 32; ++i )
{
tmp = fulladd( num1[i], num2[i] );
r += tmp << i;
putchar( tmp ? '1' : '0' );
}
putchar( carry ? '1' : '0' );
printf("\n%d\n\n%d + %d = %d", r, A, B, A+B);
return 0;
}

Can you give us more context? Where did you find this? What have you tried to do to understand it? It looks like it is doing arithmetic with bitwise operations.

1 Like

Out teacher gave us task “An ALU has 4bit adder (+), discuss how two
8bit integers can be added (+). Give
example in C Program”
I got this program online but do not know how it works. i need it to prepare for viva please help me to understand this code

Well, lets back up. What do you understand about adding 4 or 8 bit integers?

No i don’t
I just want to understand this code if you can help me with by explaining the whole code it will be helpful for me

If you are just interested in getting someone else’s code to work for you, then this question isn’t the sort I get excited about answering. I’ll let someone else answer.

2 Likes