Domanda

I need int 32 in binary as 00100000 or int 127 in binary 0111 1111. The variant Integer.toBinaryString returns results only from 1. If I build the for loop this way:

for (int i= 32; i <= 127; i + +) {
System.out.println (i); 
System.out.println (Integer.toBinaryString (i));
}

And from binary numbers I need the number of leading zeros (count leading zeros (clz) or number of leading zeros (nlz)) I really meant the exact number of 0, such ex: at 00100000 -> 2 and at 0111 1111 - > 1

È stato utile?

Soluzione 2

Count the number of leading zeros as follows:

int lz = 8;
while (i)
{
    lz--;
    i >>>= 1;
}

Of course, this supposes the number doesn't exceed 255, otherwise, you would get negative results.

Altri suggerimenti

How about

int lz = Integer.numberOfLeadingZeros(i & 0xFF) - 24;
int tz = Integer.numberOfLeadingZeros(i | 0x100); // max is 8.

Efficient solution is int ans = 8-(log2(x)+1)

you can calculate log2(x)= logy (x) / logy (2)

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)");
         }
    }
}

test statement:

int leadingZeros = new UtilsInt.leadingZerosInt(255); // 8

test output:

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top