If you are ok with the idle case n = 0 , you can simplify it to
uint64_t set_n_high(int n) { return ~UINT64_C(0) << (64 - n); }
If, in addition to this, you have everything with a βstrange number of shiftsβ (undefined behavior, but Works On My Machine), you can simplify this even further
uint64_t set_n_high(int n) { return ~UINT64_C(0) << -n; }
If you are ok with the idle case n = 64 , you can simplify it to
uint64_t set_n_high(int n) { return ~(~UINT64_C(0) >> n); }
If this means you must check n , it will not be faster. Otherwise it could be.
If you're out of order, if none of them work, it gets harder. Here is a suggestion (maybe the best way)
uint64_t set_n_high(int n) { return ~(~UINT64_C(0) >> (n & 63)) | -(uint64_t)(n >> 6); }
Note that the negation of an unsigned number is well defined.
harold
source share