Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Created September 28, 2011 19:29
Show Gist options
  • Save raheelahmad/1248966 to your computer and use it in GitHub Desktop.
Save raheelahmad/1248966 to your computer and use it in GitHub Desktop.
Problem 2.68
/*
* Mask with least signficant n bits set to 1
* Examples: n = 6 --> 0x2F, n = 17 --> 0x1FFFF
* Assume 1 <= n <= w
*/
int lower_one_mask(int n) {
/*
* 2ˆn-1 has bit pattern 0...01..1 (n 1’s)
* But, we must avoid a shift by 32
*/
return (2<<(n-1)) - 1;
}
The code makes use of the trick that (1<<n)-1 creates a mask of n ones. The only challenge is to avoid shifting by w when n = w. Instead of writing 1<<n, we write 2<<(n-1). This code will not work for n = 0, but that’s not a very useful case, anyhow.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment