找出重新present二进制正整数所需的比特数? [英] Find out number of bits needed to represent a positive integer in binary?
问题描述
这大概是pretty基本的,但对我来说节省一个小时左右的悲伤谁能告诉我如何才能制定出在Java中重新present给定的正整数所需的比特数<? / p>
例如。我得到一个小数11,(1011)。我需要得到答案,4。
我想如果我能工作,如何比最显著位以外的所有位设置为0,然后>>>吧,我会得到我的答案。但是......我不能。
好了,你可以算你有多少次转变之后,剩下的只是零右前:
int值= 11;
诠释计数= 0;
而(值大于0){
算上++;
值=价值&GT;&GT; 1;
}
This is probably pretty basic, but to save me an hour or so of grief can anyone tell me how you can work out the number of bits required to represent a given positive integer in Java?
e.g. I get a decimal 11, (1011). I need to get the answer, 4.
I figured if I could work out how to set all the bits other than the most significant bit to 0, and then >>> it, I'd get my answer. But... I can't.
Well, you can just count how many times you shift right before you're left with just zero:
int value = 11;
int count = 0;
while (value > 0) {
count++;
value = value >> 1;
}
这篇关于找出重新present二进制正整数所需的比特数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!