PLEASE ANSWER I WILL RATE YOUR ANSWER AND THUMBS UP
For the following C functions:
int q3(int x) {
return ((~x)>>31) & 0x1;
}
int q4(int x) {
int mask = x>>31;
int y= (x ^ mask);
int z = (~mask + 1);
return (y+z);
}
int q5(int x){
int y = !x;
int z = x >> 31;
z = z | y;
return !z;
}
int q6(int x) {
int result = (x<<31);
result = (result >> 31);
return result;
}
---------
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)
IMP NOTE: int in c is of 4 bytes, ie 32 bits. The most significat bit (left most) will be 1 for -ve numbers and 0 for positive numbers.
Function q3 will return 1 for positive numbers or 0 and 0 for negative numbers
~x will compliment the number and >>31 will bring the MSB to the LSB and anding with 1 will return 1 for positive numbers and 0 for -ve numbers
Here is the simpler version:
int newq3(int x)
{
if (x < 0)
return 0;
return 1;
}
q4 will always return the absolute value of the given number
mask will store the x shifter to 31 times so 1 for -ve numbers and 0 for +ve
y will be 0 for even -ve numbers and 1 for odd -ve numbers, and always 0 for +ve numbers
Then we complement the mask and add 1 to get the original number by in +ve format
Here is simpler version
int newq4(int x)
{
if (x < 0)
return x * (-1);
return x;
}
q5 will return 1 for +ve numbers and 0 for -ve numbers and 0
y becomes 1 for 0 and 0 for -ve and +ve numbers
z become the msb digits of the numbers
then z = z|b becomes 1 if z or y is 1 ( for 0 or -ve numbers) and 0 for +ve numbers
!z becomes reverse of z
Here is the simpler version
int newq5(int x)
{
if (x <= 0)
return 0;
return 1;
}
q6 returns -1 for odd numbers and 0 for even numbers
For even numbers the result clearly becomes 0 after shifting so it will remain 0 after another shift too
For odd numbers the lsb is always 1, so after left shifting 31 bits result will have 1 at the MSB and after right shifting 31 times 1 will come at lsb and sign will be preserved resulting in -1
Here is the simpler code:
int newq6(int x)
{
if (x < 0)
x = x * (-1);
if (x % 2 == 1)
return -1;
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.