Velocity Reviews > Re: Better bitmask macro

Tim Rentsch
Guest
Posts: n/a

 03-28-2012
Guillaume Dargaud <(E-Mail Removed)> writes:

> Hello all,
> I wrote this small macro to provide a bit mask from bit L to bit H:
>
> // Does a bit mask from bit L to bit H inclusive on 64 bits.
> // Warning H must be <=62 (not 63) and L<=H
> #define BITMASK(H,L) ( ((1UL<<((H)-(L)+1))-1)<<(L) )
>
> The problem is that H must not be 63.
> Is there a better way to write it so that it works with all bits ?
>
> but there's probably a better way.

( (0xFFFFFFFFFFFFFFFF >> (H) << (H) ^ 0xFFFFFFFFFFFFFFFF) >> (L) << (L) )

This definition works for implementations that have a 64-bit (or
greater) integer type, even if they don't have unsigned long long.

Tim Rentsch
Guest
Posts: n/a

 03-29-2012
Tim Rentsch <(E-Mail Removed)> writes:

> Guillaume Dargaud <(E-Mail Removed)> writes:
>
>> Hello all,
>> I wrote this small macro to provide a bit mask from bit L to bit H:
>>
>> // Does a bit mask from bit L to bit H inclusive on 64 bits.
>> // Warning H must be <=62 (not 63) and L<=H
>> #define BITMASK(H,L) ( ((1UL<<((H)-(L)+1))-1)<<(L) )
>>
>> The problem is that H must not be 63.
>> Is there a better way to write it so that it works with all bits ?
>>
>> but there's probably a better way.

>
> ( (0xFFFFFFFFFFFFFFFF >> (H) << (H) ^ 0xFFFFFFFFFFFFFFFF) >> (L) << (L) )
>
> This definition works for implementations that have a 64-bit (or
> greater) integer type, even if they don't have unsigned long long.

Urk. Off-by-one error.

( (0xFFFFFFFFFFFFFFFF >> (H) >> 1 << (H) << 1 ^ 0xFFFFFFFFFFFFFFFF) >> (L) << (L) )