我需要二进制的int 32,就像二进制0111 1111中的00100000或int 127。变体Integer.toBinaryString只返回1的结果。如果以这种方式构建for循环:
for (int i= 32; i <= 127; i + +) {
System.out.println (i);
System.out.println (Integer.toBinaryString (i));
}从二进制数来看,我需要前导零(计数前导零)或前导零数(Nlz)的数目,我实际上是指0的确切数字,例如:在00100000 -> 2和0111111->1。
发布于 2014-01-25 13:02:16
按以下方式计算前导零的数目:
int lz = 8;
while (i)
{
lz--;
i >>>= 1;
}当然,这假设数字不超过255,否则,您将得到负面的结果。
发布于 2014-01-25 13:33:50
怎么样
int lz = Integer.numberOfLeadingZeros(i & 0xFF) - 24;
int tz = Integer.numberOfLeadingZeros(i | 0x100); // max is 8.发布于 2016-06-27 13:45:36
public class UtilsInt {
int leadingZerosInt(int i) {
return leadingZeros(i,Integer.SIZE);
}
/**
* use recursion to find occurence of first set bit
* rotate right by one bit & adjust complement
* check if rotate value is not zero if so stop counting/recursion
* @param i - integer to check
* @param maxBitsCount - size of type (in this case int)
* if we want to check only for:
* positive values we can set this to Integer.SIZE / 2
* (as int is signed in java - positive values are in L16 bits)
*/
private synchronized int leadingZeros(int i, int maxBitsCount) {
try {
logger.debug("checking if bit: "+ maxBitsCount
+ " is set | " + UtilsInt.intToString(i,8));
return (i >>>= 1) != 0 ? leadingZeros(i, --maxBitsCount) : maxBitsCount;
} finally {
if(i==0) logger.debug("bits in this integer from: " + --maxBitsCount
+ " up to last are not set (i'm counting from msb->lsb)");
}
}
}测试声明:
int leadingZeros = new UtilsInt.leadingZerosInt(255); // 8测试输出:
checking if bit: 32 is set |00000000 00000000 00000000 11111111
checking if bit: 31 is set |00000000 00000000 00000000 01111111
checking if bit: 30 is set |00000000 00000000 00000000 00111111
checking if bit: 29 is set |00000000 00000000 00000000 00011111
checking if bit: 28 is set |00000000 00000000 00000000 00001111
checking if bit: 27 is set |00000000 00000000 00000000 00000111
checking if bit: 26 is set |00000000 00000000 00000000 00000011
checking if bit: 25 is set |00000000 00000000 00000000 00000001
bits in this integer from: 24 up to last are not set (i'm counting from msb->lsb)https://stackoverflow.com/questions/21350827
复制相似问题