Skip to content

chapter_2, p66.c #1

@E3798211

Description

@E3798211

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions