简体   繁体   English

32位整数的二进制表示

[英]Binary representation of a 32 bits integer

I have writen a very simple algorithm for generating the binary representation of a 32 bits integer. 我写了一个非常简单的算法来生成32位整数的二进制表示形式。

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. 下图说明了对main方法结果的调用。

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. 但是,当我将long checker = (number >> i) & 1更改为(number & intPower(2,i))时,我遇到了一个问题,它只是给我异常的结果,我真的不知道为什么。 Any help regarding this is very welcome. 任何对此的帮助都是非常欢迎的。

Imagine number is 2. In binary it's 0010 and you're comparing with intPower(2, 1) . 想象number是2。在二进制number0010 ,您正在与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 . 您正在做的是2 & 20010 & 0010 ),结果又是20010 )。如果失败,因为它与1比较。 In short what you get after & is 0 or rhs value (not always 1 / 0 like with (number >> i) & 1 ). 总之,你会得到什么后&0RHS值(不总是1 / 0(number >> i) & 1 )。

Change your code to: 将您的代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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