The keyword


Basic data types


Into the system

Base system: Base system is a counting method. In our daily life, the most commonly used is decimal number, that is, every ten one, while in the computer data storage mode is binary number, that is, every two one, common base system and octal and hexadecimal.

1. Base conversion

Conversion between hexadecimal, is the most commonly used to decimal conversion to other base, other base is converted to a decimal, and decimal also can be used as an intermediary, as in other conversion between hexadecimal, we now turn to the most commonly used decimal binary decimal and binary to as an example to explain and other hexadecimal conversion is the same:

(1) Decimal to binary

  • The value is 35 in decimal notation
  • Method: divide a decimal number by 2 in succession (divide by several base), record the remainder after each division by 2, and finally write the remainder backwards, if less than 8 bits, add 0 to the far right, this is the final binary number.

  • Since binary is usually expressed in the power of 8, it needs to be supplemented with 0, and finally the binary number of decimal 35 is 0010, 0011.

(2) Binary to decimal number

  • Binary number: 1000 1010
  • Method: Number each bit of the binary from right to left starting from 0, multiply the value of each bit by 2 to the power of the ordinal number, and add up the result of each bit to get the decimal representation of the binary number.


2. Java code to achieve base conversion

(1) Decimal to binary

public static void TentoTwo(long n) {
		long res = 0;
		int i = 1;
		while(n>0) {
			 res += n % 2 * i; 
			 n /= 2;
			 i *= 10;
		}
		System.out.println(res);
}
Copy the code

(2) Binary to decimal number

// Convert binary to decimal
public static void TwotoTen(long n) {
		long res = 0;
		int i =0;
		while(n>0) {
			res += n%10 * mi(2,i);
			n /= 10;
			i++;
		}
		System.out.println(res);
	}
// Raise something to a power, a to b
public static int mi(int a, int b) {
		if(b == 0 ) {
			return 1;  
		}else if(b == 1) {
			return a;
		}else {
   int c = a;
			for(int i = 1; i<b; i++) { a *= c; }}return a;
}
Copy the code

For more exciting content, please pay attention to wechat public number: