CSAPP-3e icon indicating copy to clipboard operation
CSAPP-3e copied to clipboard

chapter_2, p66.c

Open E3798211 opened this issue 6 years ago • 0 comments

This code does not work properly when x contains most significant bit set to 1, e.g. 0xFFFFFFFF. Maybe this solution might avoid this problem:

  1. Main idea is to shift right and add 0x1 to set bit
  2. Save if (x == 0) to return 0 in this case: unsigned add_bit = (x == 0);
  3. After setting all right bits to 1, shift right: x >>= 1;
  4. Add bit: return (x + add_bit);

So the code will look like this: int leftmost_one(unsigned x) { unsigned add_bit = (x != 0); x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); x >>= 1; return (x + add_bit); // Add 1 if x != 0, 0 otherwise }

Thanks!

E3798211 avatar Sep 01 '19 07:09 E3798211