简体   繁体   English

从位字节切片将位提取到int切片中

[英]Extract bits into a int slice from byte slice

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. 我有以下字节切片,我需要从中提取位并将它们放在[] int中,因为我打算稍后获取单个位值。 I am having a hard time figuring out how to do that. 我很难搞清楚如何做到这一点。

below is my code 下面是我的代码

data := []byte{3 255}//binary representation is for 3 and 255 is 00000011 11111111

what i need is a slice of bits -- > [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1] 我需要的是一块位 - > [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1]

What i tried 我尝试了什么

  • I tried converting byte slice to Uint16 with BigEndian and then tried to use strconv.FormatUint but that fails with error panic: runtime error: index out of range 我尝试使用BigEndian将字节切片转换为Uint16,然后尝试使用strconv.FormatUint但失败并出现错误panic: 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. 看到许多使用fmt.Printf函数的简单输出位表示数字的例子,但这对我来说fmt.Printf ,因为我需要一个int slice来进行进一步的位值访问。

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. 并将结果添加到输出切片。

Here's an implementation of it: 这是它的一个实现:

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
}

Testing it: 测试它:

fmt.Println(bits([]byte{3, 255}))

Output (try it on the Go Playground ): 输出(在Go Playground上试试):

[0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM