doujiang9887
2014-09-26 22:55
浏览 17
已采纳

我如何从一个字节中获取比特的子集?

I have a byte 0x38

b:= 0x38
fmt.Printf("%b
",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)

图片转代码服务由CSDN问答提供 功能建议

我有一个字节0x38

  b:= 0x38 \  nfmt.Printf(“%b 
”,b)
   
 
 

其中二进制为00111000。

我如何才能将此子集作为新的int? 例如,我想要7、6、5位,在这种情况下,该位将为int(1)。 第3、2、1位为int(4)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dos3018 2014-09-26 23:16
    已采纳

    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.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题