2.65
int even_ones (unsigned x)
Requirements: Return 1 when x contains an even number of 1s; 0 otherwise. Suppose an int has a w=32 bit.
Analysis: The most expected use is a loop, but the loop statement cannot be used. If one is written in a statement, it takes 32 times; Here the dichotomy is used, then the operation becomes Log232 = 5 times. The dichotomy implies a loop and simplifies the loop traversal. How to use the dichotomy method?
The title is to Judge X 1 of the odd even, you can divide X into 2, the first 16 X1 and the last 16 x2,x3=x1^x2, if X has an even number of 1,x3 must have an even number of 1, if X has an odd number of 1,x3 must have an odd number.
int even_ones (unsigned x) { +); 8 ); 4 ); 2 ); 1 ); return 1 ); }
2.66
int Leftmost_one (unsigned x)
Requirements: Generate mask indicating leftmost 1 in X. assume w=32; If x=0, then return 0;
Tip: First convert the x into a bit vector like [0..011..1]
Analysis: Here is the first place to look for the top 1 bit vector x which is the number one, should use loops, and then the loop cannot be used, here is the dichotomy. First, for example, the X is transformed into a bit vector such as [0..011..1], i.e. all bits after the highest bit 1 become 1.
int leftmost_one (unsigned x) { 1; 2 ; 4 ; 8 ; - ; 1 ); return x;}
Csapp (1): computer representation of numbers--after-school questions