2

Except using cgo, Do you know what is the best way to pack the GO object to byte slice?

We can use encoding/binary package to serialize GO struct to byte slice as far as we know but it supports only fixed-length variable so cannot support following case.

typedef struct
{
    uint32_t          foo:12;
    uint32_t          bar:9;
    uint32_t          baz:1;
    uint32_t          qux:10;
} type_t;

Do we need to implement GO struct with getter/setter for this case with terrible bit manipualtion considering endianness? Such as:

type typeT struct
{
    fooBarBazQux uint32
}
// some complex bit manipulation considering endianness
func (t typeT) getFoo() uint32 {
}
func (t typeT) setFoo(val uint32) {
}

Is there any better solution for this?

I tried encoding/json mashaler for my custom type but encoding/binary package does not seem to support this kind of interface.

I need your help.

1 Answer 1

0

The actual packing and bit order of such structures in C is not guaranteed, and may vary from one compiler to the next, even on the same machine.1 If the bit order actually matters—as it will in this case—you should probably write your own setters and getters.

Go does have built in binary encoding operations, which can let you access binary data even if it's not stored in native machine order. But you can open-code such accesses; they're not particularly complex. Similarly, doing all the bit shifting and masking for insertion and access is not difficult, it's just a bit tedious.

Cgo does not support bitfield access. Related (but no answer there): How to access C bitfield in Go; Go: Bitfields and bit packing (no support for bitfields in cgo, and none planned).


1Back in the day, on the 680x0, this was a problem when switching from the MIT C compiler to the Sun one, as they used different bit orders within words. When the 68020 introduced bitfield instructions, they numbered the bits differently from the earlier single-bit test instructions, which kind of encouraged this incompatiblity. See also Are later 68000 variants backward compatible with earlier ones?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.