In: Computer Science
create "bitty.c" that uses bitwise operators and return statements to implement the functions in "bitty.h".
"bitty.c" that can only implement "bitty.h"
_____________________________________________________________
bitty.h:
// Returns 1 if v is an even number, otherwise returns 0
unsigned char isEven(unsigned char v);
// Returns 1 if v is zero, otherwise returns 0
unsigned char isZero(unsigned char v);
// Returns 1 if a and b have the same value, otherwise 0
unsigned char equals(unsigned int a, unsigned int b);
// Returns a if a is greater than or equal to b, otherwise returns b
// You may use if but may not use comparison operators or else
// e.g. if(a) is allowed but if(a<b) and if(b==0) are not allowed
unsigned char geq(unsigned char a, unsigned char b);
// Returns the number of bits that are 1
unsigned char tally(unsigned int n);
If you understand the concept do give it a like:)
unsigned char isEven(unsigned char v){
if(v & 1)
return 0;
return 1;
}
Explanation: If v is even then rightmost bit must be equal to zero, so after anding it with 1 it will always give answer as 0
unsigned char isZero(unsigned char v){
if(v | 1)
return 0;
return 1;
}
Explanation: If v is zero then ORing it with 1 will always give answer as 0.
unsigned char equals(unsigned int a, unsigned int b){
if(a ^ b)
return 0;
return 1;
}
Explanation: XOR of 2 same numbers is always zero as XOR of same digit is 0.
unsigned char geq(unsigned char a, unsigned char b){
if(!(a ^ b))
return a;
if(!(b ^ 0) || (a / b)))){
return a;
}
return b;
}
Explanation: Here a ^ b refers to a == b , !(b ^ 0) refers to b == 0 and a/b will give us quotient as 0 if a<b or any other number if a>=b .
So, a ^ b gives us zero that means they are equal so we will return a
else we will check that if b == 0 OR a / b> 0 then we will return a other wise we will return b.
unsigned char tally(unsigned int n){
int count = 0;
while(n){
if(n & 1)
count++;
n>>=1;
}
return count;
}
Explanation: Here we are checking each bit by Anding it with 1 if we encounter 1 then we will update our counter.
I hope I am able to solve your problem, if yes then do give it a thumps up :)