BitExport

Go, Reflection -


BitExport is a simple Go package that allows for customized bit-packing when exporting structs into bytes.

The package uses the Go reflection API to find custom “bit” flags that the user places inside the struct to mark how many bits each element should be. This allows the user to use the struct like normal for the program duration but export it in a different, packed format.

The interface for the package is very simple and is demonstrated below.

type Example struct {
	a bool   `bits:"1"`
	b bool   `bits:"1"`
	c bool   `bits:"1"`
	d bool   `bits:"1"`
	e uint16 `bits:"12"`
}

test := Example {
	a: 0,
	b: 1,
	c: 1,
	d: 0,
	e: 255
}

// Encode the struct into 2 packed bytes
bytes := BitExport.ToBytes(test)

// Decode the bytes back into a struct
var decoded Example
BitExport.FromBytes(bytes, &decoded)

* Currently, the package has a locked endianness, as that was the only format necessary for UDP communications in my other project, Eos .

github link