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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试