英文:
How to unpack 2, 2 and 3 bits out of a byte
问题
假设我有3个字节(2个2位和1个3位)按照以下方式打包:
func pack(a, b, c byte) byte { // 是否有更高效的打包方法?
return a<<6 | b<<4 | c
}
func main() {
v := pack(1, 2, 6)
a := v >> 6
b := v >> 4 // 错误
c := v & 7
fmt.Println(v, a, b, c)
}
如何解包 b
?
英文:
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
?
答案1
得分: 8
你需要像你已经对c
做的那样,屏蔽掉未使用的位。我还在pack函数中添加了掩码,以防止值的意外重叠:
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论