Count bits used in int

后端 未结 11 1436
梦谈多话
梦谈多话 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条回答
  •  Happy的楠姐
    2020-12-30 16:53

    I think the rounded-up log_2 of that number will give you what you need.

    Something like:

    return (int)(Math.log(value) / Math.log(2)) + 1;
    

提交回复
热议问题