arbitrary bitsize of variables
    Daniel Keep 
    daniel.keep.lists at gmail.com
       
    Sat Sep 29 07:47:32 PDT 2007
    
    
  
dominik wrote:
> "dominik" <aha at aha.com> wrote in message 
> news:fdlnq6$f0i$1 at digitalmars.com...
>> Is it possible in D to do something like this (in C++):
>>
>> struct Testor {
>>     int small_int: 5;
>>     int even_smaller_int: 3;
>> };
>>
>> this basically says make one integer of 5 bit size, and other of 3 bit 
>> size.. whole structure is 8bits long
> 
> or is it possible to do it with the class - since, as I understood, struct 
> is always by value in D - and class is by reference.
> I have tried with C++ syntax, but it fails on : - so I presume there is 
> support for this, but I can't find correct syntax.
> 
> thanks 
No, you cannot do this directly in D.  There was once support for a
'bit' type, but it was removed in favour of the 'bool' type; note that
'bool' variables take up a whole byte, not a single bit.
Your best bet might be to do something like this:
struct Tester
{
    private ubyte storage;
    ubyte small_int()
    {
        return storage & ((1<<5)-1));
    }
    ubyte small_int(ubyte v)
    {
        return (storage = (storage & ~((1<<5)-1)) | (v & ((1<<5)-1)));
    }
    // repeat for even_smaller_int :P
}
If you don't require those precise layout requirements, there's always
std.bitarray.
	-- Daniel
    
    
More information about the Digitalmars-d-learn
mailing list