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
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?