Write code to implement the following functions:
/* Return 1 when X contains an odd number of 1 s; 0 otherwise.
Assume W = 32 .*/
Int odd_ones (unsigned X );
Your function shocould follow the bit-level integer coding rules (page 120), could t that you may assume that data type int has W = 32 bits.
Your code shoshould contain a total of at most 12 arithmetic, bit-wise, and logical operations.
Answer:
Main principles used: 1. 1 ^ 1 = 1 0 ^ 0 = 0 1 ^ 0 = 1 0 ^ 1 = 1
2. Odd-even = odd, even-even = even
For unsigned X, the 16-bit height is different from the 16-bit lower, because 1 ^ 1 = 0, the number of 1 contained in 16 bits is exactly the number of 1 in X minus the even number. And so on, get a digit after the last XOR. If it is 1, it means that X contains an odd number of 1, and if it is 0, it means that X contains an even number of 1.
To reduce the number of operations, use Part X to save part B.
Int odd_ones (unsigned X) {// use the low 16 bits of X to represent B. x ^ A corresponds to B ^ A unsigned A = x> 16; X = x ^; // use the Lower 8 bits of X to represent B a = x> 8; X = x ^ A; // use the lower 4 bits of X to represent B A = x> 4; X = x ^ A; // use the low 2 bits of X to represent B A = x> 2; X = x ^; // use the low 1 bits of X to represent B A = x> 1; X = x ^ A; // at this time, returns X & 0x1 ;}