java decimal binary

1. Convert decimal to binary

Principle: The given number is cyclically divided by 2 until the quotient is 0 or 1. Record the remainder of the division result of each step, and then get the corresponding binary in reverse

For example, 8 to binary, the first division by 2 is equal to 4 (remainder 0), the second division by 2 is equal to 2 (remainder 0), the third division by 2 is equal to 1 (remainder 0), and the last remainder is 1, and the remainder obtained in turn is 0 0 0 1

Conversely, it is 1000. The byte length of the internal representation of the computer is fixed, such as 8 bits, 16 bits, and 32 bits. Therefore, in the high-order filling, the bytecode in java is 8 bits, so the high-order filling is 00001000.

Writing method (8) 10 = (00001000) 2;

package sourceCode.hashMap;

public class mapHashCodeTest {
    
    
    public static void main(String[] args) {
    
    
        String str = toBinary(8);
        System.out.println(str);
        //运行结果:1000
    }

    static String toBinary(int num) {
    
    
        String str = "";
        while (num != 0) {
    
    
            str = num % 2 + str;
            num = num / 2;
        }
        return str;
    }

}

2. Convert binary to decimal

The calculation is also very simple. For example, the binary representation of 8 is 00001000, and the high digit is removed to be 1000. At this time, the power of 2 is calculated from the ones digit (the ones digit is 0, and pushed back in turn) multiplied by the number on the corresponding digit, and then the obtained value is added.

So, (2 to the 0th power)*0+(2 to the 1st power)*0+(2 to the 2nd power)*0+(2 to the 3rd power)*1 = 8

Code implementation, directly call Integer.parseInt("",2);

 System.out.println(Integer.parseInt("1000",2));

Running result: 8

Guess you like

Origin blog.csdn.net/klylove/article/details/122167864