complete the following c puzzles using the listed operators. no data control structures allowed (for, if, etc.)
/*
* logicalShift - shift x to the right by n, using a logic\
al shift
* Can assume that 0 <= n <= 31
* Examples: logicalShift(0x87654321,4) = 0x08765432
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int logicalShift(int x, int n) {
}
/*
* bitCount - returns count of number of 1's in word
* Examples: bitCount(5) = 2, bitCount(7) = 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 40
* Rating: 4
*/
int bitCount(int x) {
}
/*
* bang - Compute !x without using !
* Examples: bang(3) = 0, bang(0) = 1
* Legal ops: ~ & ^ | + << >>
* Max ops: 12
* Rating: 4
*/
int bang(int x) {
}
#include<stdio.h>
int logicalShift(int x, int n)
{
int mask = ~(-1 << n) << (32 - n);
return ~mask & ( (x >> n) | mask);
}
int bitCount(int x) {
int count=0;
while(x){
count+= x&1;
x>>=1;
}
return count;
}
int main(){
int x = 0x87654321;
x = logicalShift(x,4);
printf("x=%x\n",x);
printf("%d\n",bitCount(5) );
printf("%d\n",bitCount(7) );
}
Get Answers For Free
Most questions answered within 1 hours.