CSAPP (1): Computer Representation of numbers-after-school questions, after-school csapp
2.65
Int even_ones (unsigned x)
Requirement: return 1 when x contains an even number of 1 s; 0 otherwise. Assume that int has w = 32 bits.
Analysis: the loop statement is not applicable. If you write a statement one by one, it will take 32 times; here, the operation is changed to logstores = 5 times. The bipartite method implies loop while simplifying loop traversal. How does one use the bipartite method?
The question is to judge the parity of 1 in x. We can divide x into 2. For example, if the first 16-bit x1 and the last 16-bit x2, x3 = x1 ^ x2, then, 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){ x ^= (x >> 16); x ^= (x >> 8); x ^= (x >> 4); x ^= (x >> 2); x ^= (x >> 1); return !(x & 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: Convert x into a bit vector like [0 .. 011 .. 1 ].
Analysis: here we look for the first bit of the highest bit of 1 in the vector x, we should use a loop, and then the loop is not available, here we use a bipartite. First, as in [tip], convert x to a bit vector like [0 .. 011 .. 1], that is, all the bits after the highest bit 1 are changed to 1.
int leftmost_one(unsigned x){ x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x &= ~(x >> 1); return x;}