Best way to get a bit mask of 2^n ones?

71 points Inappropriate_Piano 63 comments

I need to get a u64 bit mask whose 2^n least significant bits are all ones, and the rest are zeroes, where n can range from 1 to 6. For n < 6, I can just take 2u64.pow(2u32.pow(n)) - 1. But this overflows for n = 6. My alternative was the following:

let mask = match 2u64.checked_pow(2u32.pow(n)) {
    Some(m) => m - 1,
    None => u64::MAX,
};

This does the trick, but it feels like there should be a better way to do it. Any ideas?