Count bits used in int

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

    Unfortunately there is no Integer.bitLength() method that would give you the answer directly.

    An analogous method exists for BigInteger, so you could use that one:

    BigInteger.valueOf(value).bitLength()
    

    Constructing the BigInteger object will make it somewhat less efficient, but that will only matter if you do it many millions of times.

提交回复
热议问题