Discussion in 'C Programming' started by Tim Rentsch, Mar 28, 2012.

1. ### Tim RentschGuest

Guillaume Dargaud <> 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, Mar 28, 2012

2. ### Tim RentschGuest

Tim Rentsch <> writes:

> Guillaume Dargaud <> 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.