Fastest way to enumerate through turned on bits of an integer

后端 未结 8 1380
暗喜
暗喜 2021-02-06 08:22

What\'s the fastest way to enumerate through an integer and return the exponent of each bit that is turned on? Have seen an example using << and another u

8条回答
  •  别那么骄傲
    2021-02-06 08:41

    If you won't choke on a little C++:

     void func(int i, int& n, int a[]){
      n = 0;
      if (i < 0) a[n++] = 31;
      i <<= 1;
      if (i < 0) a[n++] = 30;
      i <<= 1;
      if (i < 0) a[n++] = 29;
      i <<= 1;
    
      ...
    
      if (i < 0) a[n++] = 0;
    }
    

提交回复
热议问题