doupi1532
2019-01-24 05:01
浏览 47
已采纳

将位映射到int

I'm trying to map a uint64 array bit positions to an int array (see below). BitSet is a []uint64. Below is my code as currently setup. But I am wondering if there could be a std function in golang that can reduce this code. Other language has BitArray or other objects that makes life much easier.

So, in golang, do we have to code this? is there a better to do this?

// Indexes the index positions of '1' bits as an int array
func (b BitSet) Indexes() []int {
    // set up masks for bit ANDing
    masks := make([]uint64, _BitsPerUint64)
    for i := 0; i < _BitsPerUint64; i++ {
        masks[i] = (1 << uint(i))
    }
    // iterate bitset
    indexes := make([]int, 0, len(b)*4)
    for i := 0; i < len(b); i++ {
        for m := 0; m < _BitsPerUint64; m++ {
            if masks[m]&b[i] > 0 {
                indexes = append(indexes, i*_BitsPerUint64+m)
            }
        }
    }
    return indexes
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqp21271 2019-01-24 05:48
    已采纳
    func (b BitSet) Indexes() []int {
        retval := make([]int, 0, len(b)*64)
        for idx, value := range b {
            for i := 0; i < 64; i++ {
                if value & (1<<uint(i)) != 0 {
                    retval = append(retval, idx*64 + i)
                }
            }
        }
        return retval
    }
    
    
    点赞 评论

相关推荐 更多相似问题