Count bits used in int

后端 未结 11 1432
梦谈多话
梦谈多话 2020-12-30 15:54

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:

11条回答
  •  独厮守ぢ
    2020-12-30 16:33

    From here, a way to do it with just bitwise-and and addition:

    int GetHighestBitPosition(int value) {
      if (value == 0) return 0;
    
      int position = 1;
      if ((value & 0xFFFF0000) == 0) position += 16;
      if ((value & 0xFF00FF00) == 0) position += 8;
      if ((value & 0xF0F0F0F0) == 0) position += 4;
      if ((value & 0xCCCCCCCC) == 0) position += 2;
      if ((value & 0xAAAAAAAA) == 0) position += 1;
    
      return position;
    }
    

提交回复
热议问题