What’s the best way to fill a variable with an unknown (at compile time) number of ones? For example, let’s say:
int n = 5;
int b = fillwithones(5);
now b contains 11111 (in binary).
I can’t just hard code int b = 31 because n is not known ahead of time (in my application).
I could do something like this:
int b = pow(2, n) - 1
But using a pow seems very wasteful.
Thanks!
You can use left shift and then subtract 1:
The reason this works is 1 shifted left n times is the same as 2n, as each sole bit position represents a power of 2.