如何从一个字节中解包2、2和3位。

huangapple go评论83阅读模式
英文:

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&lt;&lt;6 | b&lt;&lt;4 | c
}

func main() {
	v := pack(1, 2, 6)
	a := v &gt;&gt; 6
	b := v &gt;&gt; 4 // wrong
	c := v &amp; 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&lt;&lt;6 | b&amp;twoBits&lt;&lt;4 | c&amp;threeBits
}

func main() {
	v := pack(1, 2, 6)
	a := v &gt;&gt; 6
	b := v &gt;&gt; 4 &amp; twoBits
	c := v &amp; threeBits
	fmt.Println(v, a, b, c)
}

huangapple
  • 本文由 发表于 2016年4月13日 04:32:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/36583504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定