Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Re: Better bitmask macro

Reply
Thread Tools

Re: Better bitmask macro

 
 
Tim Rentsch
Guest
Posts: n/a
 
      03-28-2012
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
> // Example: BITMASK(5,3)=0x1C
> #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 ?
>
> I can think of adding (H)==63 ? ... : BITMASK(H,L)
> but there's probably a better way.


#define BITMASK(H,L) \
( (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.
 
Reply With Quote
 
 
 
 
Tim Rentsch
Guest
Posts: n/a
 
      03-29-2012
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
>> // Example: BITMASK(5,3)=0x1C
>> #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 ?
>>
>> I can think of adding (H)==63 ? ... : BITMASK(H,L)
>> but there's probably a better way.

>
> #define BITMASK(H,L) \
> ( (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.

#define BITMASK(H,L) \
( (0xFFFFFFFFFFFFFFFF >> (H) >> 1 << (H) << 1 ^ 0xFFFFFFFFFFFFFFFF) >> (L) << (L) )
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Better bitmask macro Eric Sosman C Programming 3 03-29-2012 05:51 AM
The Hack of bitmask used as Predicate Parameters Xah Lee Java 0 04-23-2007 10:53 AM
Schema representation of a "bitmask" type? Andrey Brozhko XML 1 12-10-2004 05:12 PM
Bitmask & Graphics Question Rod Nibbe Java 2 10-26-2004 03:56 PM
Bitmask representation of integers =?iso-8859-9?Q?Tongu=E7?= Yumruk Python 3 10-08-2003 02:50 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57