Count bits used in int

后端 未结 11 1462
梦谈多话
梦谈多话 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:58

    If you are looking for the fastest (and without a table, which is certainly faster), this is probably the one:

    public static int bitLength(int i) {
        int len = 0;
    
        while (i != 0) {
            len += (i & 1);
            i >>>= 1;
        }
    
        return len;
    
    }
    

提交回复
热议问题