Set n highest bits twiddling

Viewed 338

I have the following function that sets the N highest bits, e.g. set_n_high(8) == 0xff00000000000000

uint64_t set_n_high(int n)
{
    uint64_t v = 0;
    int i;
    for (i = 63 ; i > 63 - n; i--) {
        v |= (1llu << i);
    }

    return v;
}

Now just out of curiosity, is there any way in C to accomplish the same without using a loop (or a lookup table) ?

EDIT: n = 0 and n = 64 are cases to be handled, just as the loop variant does.

6 Answers
Related