Go: Bitfields and bit packing

Rooke picture Rooke · Apr 26, 2011 · Viewed 7.9k times · Source

The C language's bitfields provide a fairly convenient method of defining arbitrary-width fields within a structure (nevermind the problems with portability for a minute.) For example, here's a simple structure with a couple fields and a 'flag':

#pragma pack(push,1)
struct my_chunk{

    unsigned short fieldA: 16;
    unsigned short fieldB: 15;
    unsigned short fieldC:  1;
};
#pragma pop()

Adding the #pragma statements packs this structure into a 32-bit word (ensuring that pointer manipulations of my_chunk pointers are aligned, for example, along with space savings).

Accessing each field is syntactically very nice:

struct my_chunk aChunk;
aChunk.fieldA = 3;
aChunk.fieldB = 2;
aChunk.fieldC = 1;

The alternate way of doing this without the language's help is rather ugly and pretty much devolves into assembler. e.g. one solution is to have bitshift macros for each field you want to access:

#define FIELD_A  0xFF00
#define FIELD_B  0x00FE
#define FIELD_C  0x0001

#define get_field(p, f) ((*p)&f)
#define set_field(p, f, v) (*p) = (v<<f) + (*p)&(~f)

...
set_field(&my_chunk, FIELD_A, 12345);

.. or something roughly like that (for more formality, take a look at this)

So the question is, if I want to "do" bitfields in go, what is the best practice for doing so?

Answer

peterSO picture peterSO · Apr 26, 2011

"There are no current plans for struct bitfields in Go."

You could write a Go package to do this; no assembler is required.