Assuming I have 3 bytes (2x2bits and 1x3bits) packed like this:
func pack(a, b, c byte) byte { // is there a more efficient way to pack them?
return a<<6 | b<<4 | c
}
func main() {
v := pack(1, 2, 6)
a := v >> 6
b := v >> 4 // wrong
c := v & 7
fmt.Println(v, a, b, c)
}
How do I unpack b
?
You need to mask off the unused bits like you've already done for c
. I also added masks to the pack function, to prevent accidental overlapping of values:
const (
threeBits = 0x7
twoBits = 0x3
)
func pack(a, b, c byte) byte {
return a<<6 | b&twoBits<<4 | c&threeBits
}
func main() {
v := pack(1, 2, 6)
a := v >> 6
b := v >> 4 & twoBits
c := v & threeBits
fmt.Println(v, a, b, c)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With