interfacing C bitfield structs

Don Clugston dac at nospam.com.au
Mon Mar 20 01:14:02 PST 2006


Wolfgang Draxinger wrote:
> Walter Bright wrote:
> 
>> Add two member functions for each:
>>
>>     bool fBinary() { return BITS & 1; }
>>     bool fBinary(bool b) { BITS |= b; return b; }
>>
>>     bool fParity() { return (BITS & 2) != 0; }
>>     bool fParity(bool b) { BITS |= b << 1; return b; }
>>
>> and then, because functions work like properties, you can use
>> them as if they were properties.
> 
> These set functions won't work if b==0, since it's just an OR.
> What's needed is 
> 
> BITS = (BITS & ~(1<<n)) | b ? 1<<n : 0 ;

Or you could do

BITS = (BITS & ~(1<<n)) | (b << n) ;
to remove the need for a branch instruction.
Works just as well for multiple bits, eg for b = 0..7:
BITS = (BITS & ~(7<<n)) | (b << n) ;


I really think it would be worth adding some functions to Phobos for 
this sort of thing, and it should also duplicate the bit functions from
std.intrinsic. (I don't think the fact that bsr is an intrinsic should 
be exposed in application code. It might not be true on all processors).

I have a few functions for it in my MathExtra library.
Anyone have any ideas of what it should be called?

"std.bitops"?
"std.bitoperations"?
"std.bitmanip" ?
"std.bittwiddle" ?






More information about the Digitalmars-d mailing list