In C complete each of the functions using only straightline code no loops or con
ID: 3881320 • Letter: I
Question
In C complete each of the functions using only straightline code no loops or conditionals and only using the legal operators listed for each function.
/*
* allOddBits - return 1 if all odd-numbered bits in word set to 1
* Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 6
*/
int allOddBits(int x) {
return 2;
}
/*
* conditional - same as x ? y : z
* Example: conditional(2,4,5) = 4
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 4
*/
int conditional(int x, int y, int z) {
return 2;
}
/*
* bitCount - returns count of number of 1's in word
* Examples: bitCount(5) = 2, bitCount(7) = 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 40
* Rating: 2
*/
int bitCount(int x) {
return 2;
}
/*
* minusTwo - return a value of -2
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 2
* Rating: 12
*/
int minusTwo(void) {
return 2;
}
/*
Explanation / Answer
int allOddBits(int x) {
//Initializing data_val : 0xAAAAAAAA
int data_val = (0xAA << 8) + 0xAA;
data_val = (data_val << 16) + data_val;
return !((x & data_val) ^ data_val);
}
int conditional(int x, int y, int z) {
return z ^ (((!x) + ~0) & (y ^ z));
}
int bitCount(int x) {
int count_val = 0x11 + (0x11 << 8) + (0x11 << 16) + (0x11 << 24);
int count = x & count_val;
int total = 0;
int addcount_val = 0x0F;
x = x >> 1;
count += x & count_val;
x = x >> 1;
count += x & count_val;
x = x >> 1;
count += x & count_val;
total += (count & addcount_val) + ((count >> 4) & addcount_val) + ((count >> 8) & addcount_val) + ((count >> 12) & addcount_val) + ((count >> 16) & addcount_val) +
((count >> 20) & addcount_val) + ((count >> 24) & addcount_val) + ((count >> 28) & addcount_val);
return total;
}
int minusTwo(void) {
return 2;
}