dpba63888 2017-08-05 01:10
浏览 244
已采纳

在Golang中,如何计算字节中有多少个比特?

Suppose I have two variables, that only use 6 bits:

var a byte = 31  // 00011111
var b byte = 50  // 00110010

The first (a) have more one bits than the b, however the b is greater than a of course, so is not possible use a > b.

To achieve what I need, I do one loop:

func countOneBits(byt byte) int {
    var counter int
    var divider byte

    for divider = 32; divider >= 1; divider >>= 1 {
        if byt & divider == divider {
            counter++
        }

    }

    return counter
}

This works, I can use countOneBits(a) > countOneBits(b)...


But I don't think is the best solution for this case, I don't think this need a loop and because of it I'm here.

Have a better alternative (in performance aspect) to count how many 1 have in six bits?

  • 写回答

4条回答 默认 最新

  • dongnaota6386 2017-08-05 01:22
    关注

    Given that the input is a single byte probably a lookup table is the best option... only takes 256 bytes and you get code like

    var count = bitcount[input];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部