英文:
How do i get a subset of bits from a byte?
问题
我有一个字节 0x38
b:= 0x38
fmt.Printf("%b\n",b)
它的二进制表示是 00111000。
我如何将其作为一个新的整数获取其中的一个子集?
例如,我想要获取第 7、6、5 位,这将是整数 1。
或者获取第 3、2、1 位,这将是整数 4。
英文:
I have a byte 0x38
b:= 0x38
fmt.Printf("%b\n",b)
Which is 00111000 in binary.
How can i get a subset of this as a new int?
For exampe i want bit 7,6,5 which in this case will be int(1).
Or bit 3,2,1 which will be int(4)
答案1
得分: 3
要获取高位,您可以将值向右移动。
bits765 := b >> 5
要获取中间的位,您可以将它们向右移动,然后屏蔽掉不需要的位:
bits321 := (b >> 1) & 7
英文:
To get the upper bits you can shift the value to the right
bits765 := b >> 5
To get bits in the middle you can shift them and then mask off unwanted bits:
bits321 := (b >> 1) & 7
答案2
得分: 3
一个更通用的方法,允许你选择无序的位,可以像这样实现:
// subset 必须按照从低到高的顺序排列
func bits(b uint, subset ...uint) (r uint) {
i := uint(0)
for _, v := range subset {
if b&(1<<v) > 0 {
r = r | 1<<uint(i)
}
i++
}
return
}
func main() {
fmt.Println(bits(0x38, 5, 6, 7), "x", 0x38>>5)
fmt.Println(bits(0x38, 2, 4, 5))
fmt.Println(bits(0x38, 1, 2, 3), "x", (0x38>>1)&7)
}
请注意,对于连续的子集,@Guffa 的解决方案速度更快。
英文:
A more generic approach that would allow you to pick unordered bits would be something like:
// subset has to go from lowest to highest
func bits(b uint, subset ...uint) (r uint) {
i := uint(0)
for _, v := range subset {
if b&(1<<v) > 0 {
r = r | 1<<uint(i)
}
i++
}
return
}
func main() {
fmt.Println(bits(0x38, 5, 6, 7), "x", 0x38>>5)
fmt.Println(bits(0x38, 2, 4, 5))
fmt.Println(bits(0x38, 1, 2, 3), "x", (0x38>>1)&7)
}
Keep in mind that for an sequential subset, @Guffa's solution is much faster.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论