In: Computer Science
PLEASE SOLVE I WILL THUMBS UP AND RATE YOUR ANSWER WELL
For the following two C functions:
int q1(int x) {
int m8 = 0x55;
int m16 = m8 | m8 << 8;
int m32 = m16 | m16 <<16;
int z = x | m32;
return !(~z);
}
int q2(int x) {
int m8 = 0x55;
int m16 = m8 | m8 << 8;
int m32 = m16 | m16 <<16;
int z = x & m32;
return !!z;
}
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)
So talking about first function q1 so it initializes m8 = 0x55
m8 = 00000000 01011000
m8 << 8 = 01011000 00000000 //shifts left by 8 times
now m16 = m8 | m8<<8 //Bitwise OR of m8 and m8<<8
that will be m16 = 01011000 01011000
similarly
m16 << 16 = 01011000 01011000 00000000 00000000
so m32 = m16 | m16 << 16
m32 = 01011000 01011000 01011000 01011000
now z = x | m32 // x is passed from argument is done Bitwise OR with m32
return !(~z) //so here basically '~' toggles every bit of z and '!' is not so atlast it return 0
now in function q2 m32 is similarly calculated as above
m32 = 01011000 01011000 01011000 01011000
now z = x & m32;
now x is done Bitwise AND with m32 stored in z
and return !!z not of not will be 1 if z is any number else than 0 if z is zero then not of not of 0 will be 0
now coming to your second question any simpler version i think this is simpler nothing complex