Table of contents
Part of nurago, a collection of independent Go packages for backend services.
import "github.com/tecnickcom/nurago/pkg/enumbitmap"
Package enumbitmap encodes a set of enumeration values as an integer bitmap and decodes it back.
Each bit corresponds to a unique enumeration value. The package processes up to 32 bit positions (1«0 through 1«31).
Contract:
Enum IDs must be distinct single-bit powers of two in the range 1«0 through 1«31. An ID of 0, or any multi-bit value, cannot be represented as a set bit and is therefore never produced by BitMapToStrings; such IDs make encoding and decoding asymmetric and should be avoided. The value 0 always decodes to an empty slice.
Portability:
Values are treated as the low 32 bits of a host int. Bit 31 is the sign bit on platforms where int is 32 bits wide, so this package is intended for 64-bit platforms; on a 32-bit build, inputs at or above 1«31 behave in implementation-defined ways and should be avoided.
Example with 8 bits:
00000000 = 0 dec = NONE
00000001 = 1 dec = FIRST
00000010 = 2 dec = SECOND
00000100 = 4 dec = THIRD
00001000 = 8 dec = FOURTH
00010000 = 16 dec = FIFTH
00100000 = 32 dec = SIXTH
01000000 = 64 dec = SEVENTH
10000000 = 128 dec = EIGHTH
00001001 = 1 + 8 = 9 dec = FIRST + FOURTH
When To Use
- A set of flags is stored in one integer column or transmitted as one number.
- You want the mapping between names and bit positions kept in one place.
Example
// create a binary map
// each bit correspond to a different entry (IDs are single-bit powers of two)
eis := map[int]string{
1: "first", // 00000001
2: "second", // 00000010
4: "third", // 00000100
8: "fourth", // 00001000
16: "fifth", // 00010000
32: "sixth", // 00100000
64: "seventh", // 01000000
128: "eighth", // 10000000
}
// convert binary code to a slice of strings
s, err := enumbitmap.BitMapToStrings(eis, 0b00101010) // 42
if err != nil {
log.Fatal(err)
}
fmt.Println(s)
// Output:
// [second fourth sixth]
Full source is in example_enumbitmap_test.go. More runnable examples are on pkg.go.dev.
Dependencies
This package reaches no external module: it uses only the Go standard library.