Search code examples
javastructstructurejnabit

JNA: How can I define a structure with fields of custom bit sizes?


For example, I have the following C++ structure...

struct dleaf_t
{
    int                 contents;           // OR of all brushes (not needed?)
    short               cluster;            // cluster this leaf is in
    short               area : 9;           // area this leaf is in
    short               flags : 7;          // flags
    short               mins[ 3 ];          // for frustum culling
    short               maxs[ 3 ];
    unsigned short      firstleafface;      // index into leaffaces
    unsigned short      numleaffaces;
    unsigned short      firstleafbrush;     // index into leafbrushes
    unsigned short      numleafbrushes;
    short               leafWaterDataID;    // -1 for not in water

    //!!! NOTE: for maps of version 19 or lower uncomment this block
    /*
    CompressedLightCube ambientLighting;    // Precaculated light info for entities.
    short           padding;        // padding to 4-byte boundary
    */
};

Normally I can represent structures easily in Java with JNA, but this structure uses custom bit amounts for the data types (if I'm not mistaken).

For instance, area is a short of 9 bits, rather than 16 bits like usual. flags is a short of 7 bits... etc.

How can I define a JNA structure with data types of custom bit sizes?


Solution

  • Merge the two bit fields into a single int field, and then write member methods to extract the values for the individual fields which have been combined, e.g.

    public int area_flags;
    public int getArea() { return area_flags & 0x1FF; }
    public int getFlags() { return (area_flags >> 9) & 0x3F; }
    

    You may need to play around with that a bit depending on how your compiler packs the bits.