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)

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?