从字节切片中将位提取到int切片中 [英] Extract bits into a int slice from byte slice
问题描述
我有以下字节切片,我需要从中提取比特并将它们放置在[] int中,因为我打算稍后获取各个比特值.我很难弄清楚该怎么做.
I have following byte slice which from which i need to extract bits and place them in a []int as i intend to fetch individual bit values later. I am having a hard time figuring out how to do that.
下面是我的代码
data := []byte{3 255}//binary representation is for 3 and 255 is 00000011 11111111
我需要的是一点点-> [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]
what i need is a slice of bits -- > [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]
我尝试了
- 我尝试使用BigEndian将字节片转换为Uint16,然后尝试使用
strconv.FormatUint
,但是失败,并显示错误panic: runtime error: index out of range
- 看到了许多示例,这些示例使用
fmt.Printf
函数简单地输出了数字的位表示形式,但对我来说却没有用,因为我需要一个int切片来进一步访问位值.
- I tried converting byte slice to Uint16 with BigEndian and then tried to use
strconv.FormatUint
but that fails with errorpanic: runtime error: index out of range
- Saw many examples that simple output bit representation of number using
fmt.Printf
function but that is not useful for me as i need a int slice for further bit value access.
我需要在这里使用移位运算符吗?任何帮助将不胜感激.
Do i need to use bit shift operators here ? Any help will be greatly appreciated.
推荐答案
一种方法是遍历字节,并使用第二遍循环逐位移动字节值并使用位掩码测试位.并将结果添加到输出切片中.
One way is to loop over the bytes, and use a 2nd loop to shift the byte values bit-by-bit and test for the bits with a bitmask. And add the result to the output slice.
这是它的一个实现:
func bits(bs []byte) []int {
r := make([]int, len(bs)*8)
for i, b := range bs {
for j := 0; j < 8; j++ {
r[i*8+j] = int(b >> uint(7-j) & 0x01)
}
}
return r
}
测试:
fmt.Println(bits([]byte{3, 255}))
输出(在游乐场上尝试):
[0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
这篇关于从字节切片中将位提取到int切片中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!