Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack 2, 2 and 3 bits out of a byte

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?

like image 297
OneOfOne Avatar asked Feb 07 '23 06:02

OneOfOne


1 Answers

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)
}
like image 128
JimB Avatar answered Feb 11 '23 21:02

JimB