In: Computer Science
please explain how does the following C code work.
a)
int function1(int num1, int num2) {
int num = num1 ^ num2;
int result = 0;
while(num > 0) {
result += (num & 1);
num >>= 1;
}
return result;
}
b)
int function2(unsigned int num) {
return num & ~(num - 1);
}
c)
int f1(unsigned int x) {
int count = 0;
while(x) {
count++; x = x&(x-1);
}
return count;
}
d) double ldexp(double x, int exponent) is a C math function
that returns x multiplied
by 2 raised to the power of exponent. How many narrowing and how
many promotions
happen automatically in the following code line? Name them one by
one and explain each
one separately.
float f = 2.2f * ldexp(24.4, 3.0 * 2) - 4.4;
e)
int main() {
int a[] = {1, 2, 3, 4, 5};
int *b = a; int **c = &b;
printf("%d\n", **c*2);
printf("%d\n", **c-2*4);
printf("%d\n", **c+1-*b+1);
return 0;
}
Thanks!
a)
int function1(int num1, int num2) {
int num = num1 ^ num2; //so ^ sign means Bitwise XOR between num1
and num2 and stored in num
int result = 0;
while(num > 0) { //this loop will till num is greater than
zero
result += (num & 1); // now here num is done Bitwise AND with 1
means basically it checks the last bit is 1 or 0 //and result is
keeping count of 1
num >>= 1; //this shifts the num right by 1
}
return result;
}
//So basically this code counts the no. of 1's present in num which XOR of num1 and num2
****************************************************************************************************************
b.
int function2(unsigned int num) {
return num & ~(num - 1); //So here basically num in done
Bitwise AND with complement of num-1
} //for exmaple if num = 9 return value will 1001 & 0111
therefore it will 0001
*******************************************************************************************************************
c.
int f1(unsigned int x) {
int count = 0;
while(x) {
count++;
x = x&(x-1); //Here x is done Bitwise AND with x-1 and
saving it in x again and keeping the count of it
}
return count;
}