How to calculate 2^n-1 efficiently without overflow?

Posted by Ludwig Weinzierl on Stack Overflow See other posts from Stack Overflow or by Ludwig Weinzierl
Published on 2010-06-13T16:19:51Z Indexed on 2010/06/13 16:22 UTC
Read the original article Hit count: 265

Filed under:
|

I want to calculate 2^n-1 for a 64bit integer value. What I currently do is this

for(i=0; i<n; i++) r|=1<<i;

and I wonder if there is more elegant way to do it. The line is in an inner loop, so I need it to be fast.

I thought of

  r=(1ULL<<n)-1;

but it doesn't work for n=64, because << is only defined for values of n up to 63.

© Stack Overflow or respective owner

Related posts about c

    Related posts about bit-twiddling