简体   繁体   中英

Binary representation of a 32 bits integer

I have writen a very simple algorithm for generating the binary representation of a 32 bits integer.

Here is my code:

public class NumberManipulator {

public static final int HEAVIEST_BIT = 32;


public static long intPower(int value, int power) {
    if (0== power) {
        return 1;
    }

    long result = 1;
    for (int i = 1; i <= power; i++) {
        result = result * value;
    }
    return result;
}


public static void main(String[] args) {

    int n1 = 7;
    int n2 = 18;
    int n3 = 65;
    int n4 = 11;

    System.out.println(getBinaryRepresentationOf(n1));
    System.out.println(getBinaryRepresentationOf(n2));
    System.out.println(getBinaryRepresentationOf(n3));
    System.out.println(getBinaryRepresentationOf(n4));

}

public static String getBinaryRepresentationOf(int number) {
    StringBuilder resultBuilder = new StringBuilder();

    for (int i =  HEAVIEST_BIT-1;  i >= 0; i--) {

        long checker = (number >> i) & 1; // (number & intPower(2,i));    (number >> i) & 1; 
        if (checker == 1 ) {
            resultBuilder.append("1");
        } else {
            resultBuilder.append("0");
        }
    }
    return resultBuilder.toString();
}

This code is working fine. The following image illustrate the call to the main's method results.

32位数字的二进制表示

I am however facing an issue when I change long checker = (number >> i) & 1 by (number & intPower(2,i)) , it simply gives me aberrant results and I really can't figure out why. Any help regarding this is very welcome.

Imagine number is 2. In binary it's 0010 and you're comparing with intPower(2, 1) . What you're doing is 2 & 2 ( 0010 & 0010 ), result is 2 again ( 0010 ).Your if will fail because it compares with 1 . In short what you get after & is 0 or rhs value (not always 1 / 0 like with (number >> i) & 1 ).

Change your code to:

if (checker != 0) {
    resultBuilder.append("1");
} else {
    resultBuilder.append("0");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM