java binary conversion widget (other binary to decimal)

Learn, every day down!

Ary

  • Binary (Plus before the number 0b, this number represents the binary number), A binary full by two substantially 0 and 1 digits
  • Octal(Plus before the number 0, this number represents the octal), Eight into a full, by the eight basic numbers 6,7,
  • Decimal (Before the number ... nothing, compared to the number of decimal), Over a decade (used in daily life), the 0,1,2,3, 4, 5, 6, 7, 8, 9 ten basic digits
  • Hex (Plus before the number 0x, this number represents the hexadecimal number), Over a hex, a 0,1,2,3, 4, 5, 6, 7, 8, 9 and the letters A to F (or a to f) consisting of
    同一个数进制越大,所代表的值就越大

rule:

Number: 123456
Binary === "Decimal: 1 *2 ^5 + 2 *2 ^4 + 3 *2 ^3 + 4 *2 ^2 + 5 *2 ^1 + 6 *2 ^0 = ......
规律:this number (123456) from right to left from scratch No, this number is multiplied by the value of every digit (123456) radix (binary, 2) the number and power of, is the result of a decimal conversion. Similarly other hex
code implementation:

public class sys {
    public static void main(String[] args) {
        sysHeavyLoad SYS = new sysHeavyLoad();
        System.out.println(SYS.$SYS(100, "0B"));
    }
}
public class sysHeavyLoad {
    public static int $SYS(String number, String type) {
        int sum = 0;
        char[] array = number.toCharArray();
        sum = summation(array, type);
        return sum;
    }

    public static int $SYS(int number, String type) {
        int sum = 0;
        char[] array = String.valueOf(number).toCharArray();
        sum = summation(array, type);
        return sum;
    }

    /**
     * 返回次方值
     */
    public static int power(int a, int b) {
        int power = 1;
        for (int c = 0; c < b; c++)
            power *= a;
        return power;
    }

    /**
     *判断类型并将转换结果返回
     */
    public static int summation(char[] array, String type) {
        int m = 0;
        int sum = 0;
        //二进制
        if ("0b".equals(type) || "0B".equals(type)) {
            m = 2;
        }
        //八进制
        if ("0".equals(type)) {
            m = 8;
        }
        //十六进制
        if ("0x".equals(type) || "0X".equals(type)) {
            m = 16;
        }
        for (int i = 0; i < array.length; i++) {
            sum = sum + (array[i] - '0') * power(m, array.length - i - 1);
        }
        return sum;
    }
}
Published 53 original articles · won praise 14 · views 6670

Guess you like

Origin blog.csdn.net/weixin_43160780/article/details/104640207