One*_*One 4 bit-manipulation bit-shift go
假设我有3个字节(2x2bits和1x3bits)这样打包:
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)
}
Run Code Online (Sandbox Code Playgroud)
我如何打开包装b
?
你需要像你已经做的那样掩盖未使用的位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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
110 次 |
最近记录: |