Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chapter_2, p66.c #1

Open
E3798211 opened this issue Sep 1, 2019 · 0 comments
Open

chapter_2, p66.c #1

E3798211 opened this issue Sep 1, 2019 · 0 comments

Comments

@E3798211
Copy link

E3798211 commented Sep 1, 2019

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant