interfacing C bitfield structs

Chris Miller chris at dprogramming.com
Mon Mar 20 02:49:58 PST 2006


On Mon, 20 Mar 2006 04:14:02 -0500, Don Clugston <dac at nospam.com.au> wrote:

> 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've attached code to simplify this. Here's example usage:

struct FlagTest
{
    uint bits;

    mixin .BitFlag!(uint, bits, 0x1) foo;
    mixin .BitFlag!(uint, bits, 0x2) bar;
    mixin .BitFlag!(uint, bits, 0x4) baz;
}

FlagTest ftest;

ftest.foo.flag = true;
ftest.bar.flag = false;
ftest.baz.flag = true;

assert(ftest.bits == 0b101);
assert(ftest.foo.flag == true);
assert(ftest.bar.flag == false);
assert(ftest.baz.flag == true);


If only the name in the mixin (if matching mixin name) could be promoted  
to the name of the mixin identifier, it could elegantly become: ftest.foo  
= true; e.g.:

template Foo() { int Foo = 33; }
mixin Foo bar; // The int Foo in the template could become named bar and  
allow:
assert(bar == 33);
bar = 22; // etc..


Note: the attached code would look a bit nicer if it wasn't for the  
digitalmars.D.bugs I just posted.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: bits.d
Type: application/octet-stream
Size: 2045 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20060320/432e6ba7/attachment.obj>


More information about the Digitalmars-d mailing list