Bitfield accessors

bearophile bearophileHUGS at lycos.com
Mon Nov 19 02:49:54 PST 2007


Until D gains C-style bitfields it can be created a compile-time function that returns the pairs of methods that take/return ubyte/ushort/uint/ulong, to be used by a mixin. Something like:

union TyIntFloat {
  int      i;                 // as integer
  float    f;                 // as float 
  // as bit fields:
  mixin(Bitfields!("i       
                   sign 1
                   biasedexponent 8
                   significand 23"));
}

Here "i" is the name of the unsigned integral variable to be splitted in bit fields.
std.string.split works at compile time too, it can be used to split the input string.
Something like that can be useful in Tango too (if not already present), but I presume it's difficult to make it optimize the code produced.

That
Bitfields!("i sign 1 biasedexponent 8 significand 23")
is supposed to return a string of code that contains six methods like:
"
uint sign()                 { return i & ...; }
void sign(uint x)           { i = ...; }
uint biasedexponent()       { return ...; }
void biasedexponent(uint x) { i = ...; }
uint significand()          { return ...; }
void significand(uint x)    { i = ...; }
"

The sum of the numbers is cheeked to be 8, 16, 32 or 64. According to such total that "i" variable and the input/output values have type as ubyte, ushort, uint or ulong.

Bye and thank you,
bearophile


More information about the Digitalmars-d-learn mailing list