In: Computer Science
PLEASE ANSWER I WILL RATE YOUR ANSWER AND THUMBS UP
For the following C functions:
int q7(int x) {
return x & (~x+1);
}
int q8(int x, int m, int n) {
int a = ~m+1;
int b = ~x +1;
a = x + a;
b = b + n;
return !((a|b) >> 31);
}
int q9(int x, int n) {
/* assume x and n are not a negative integer */
int temp = (1 << n);
int z = temp + ~0;
return (z & x);
}
---------------
Part i) Explain what each function does without running the code. EXPLAIN YOUR ANSWER OR YOU WILL NOT RECEIVE CREDIT.
Part ii) For each of the above functions, write a simpler version of the function (if there is one)
Let us analyze each of the fuction,
Given function,
A)
int q7(int x) {
return x & (~x+1);
}
i) Explaination: Given function computes bitwise and with its compliment plus one, and therefore returns 1 if least significiant bit 1, else return 2 for least significiant bit 0.
ii) above function already in simpler form.
B)
int q8(int x, int m, int n) {
int a = ~m+1;
int b = ~x +1;
a = x + a;
b = b + n;
return !((a|b) >> 31);
}
i) Explaination: given function q8 takes 3 input parameter and computes bitwise compliment for first and second integer bit + 1, and add integer first integer with computed second bitwise integer store as int a, and second with third integer store as b, returns compliment of bitwise a or b shifting 31 bits to right. in simpler words we simply divide a | b with 2, 31 times, so function already in simpler form.
C)
int q9(int x, int n) {
/* assume x and n are not a negative integer */
int temp = (1 << n);
int z = temp + ~0;
return (z & x);
}
i) Explaination: function q9 takes two integer, shift bitwise left which means multiplying with 2 second integer n and store in temp, integer z stores temp subtracted with one, since bitwise compliment of 0 returns -1, finally return bitwise and of z and first integer x parameter.
In simpler words always integer second parameter or n value will be returned.
ii) More simplified version:
int q9(int x, int n) {
/* assume x and n are not a negative integer */
return n;
}