java二进制、八进制、十六进制间转换详细

来源:互联网 发布:网络黑客电影国产 编辑:程序博客网 时间:2024/06/05 19:14

1.各进制表示

java里不能使用前置表示2进制,只能是 8,10,16进制
8: 前置 0
10: 不需前置
16: 前置 0x 或者 0X

public class test {    public static void main(String[] args) {        int octalB = 012;        int hexB = 0x12;        System.out.println(octalB);        System.out.println(hexB);    }}

输出结果

8进制012->10进制1016进制0x12->10进制18

2.转换-Integer.toBinaryString

测试代码

public class test {    public static void main(String[] args) {         //8进制、10进制、16进制转为2进制         System.out.println("Integer.toBinaryString(01)="+Integer.toBinaryString(01));         System.out.println("Integer.toBinaryString(012)="+Integer.toBinaryString(012));         System.out.println("Integer.toBinaryString(10)="+Integer.toBinaryString(10));         System.out.println("Integer.toBinaryString(0xa)="+Integer.toBinaryString(0xa));         System.out.println("Integer.toOctalString(0x12)="+Integer.toOctalString(0x12));         System.out.println("Integer.toOctalString(18)="+Integer.toOctalString(18));         System.out.println("Integer.toHexString(012)="+Integer.toHexString(012));         System.out.println("Integer.toHexString(10)="+Integer.toHexString(10));    }}

测试结果

Integer.toBinaryString(01)=1Integer.toBinaryString(012)=1010Integer.toBinaryString(10)=1010Integer.toBinaryString(0xa)=1010Integer.toOctalString(0x12)=22Integer.toOctalString(18)=22Integer.toHexString(012)=aInteger.toHexString(10)=a

源码

toBinaryString、toOctalString、toHexString都类似,则以toBinaryString为例讲解
Integer.java

/** * Converts the specified integer into its binary string representation.  * 将指定的整型转换为二进制表示 * The returned string is a concatenation of '0' and '1' characters. * 返回的字符串是以'0'、'1'连接的 * @param i  the integer to convert.要转换的整型值 * @return the binary string representation of {@code i}. * 返回的二进制字符串 */public static String toBinaryString(int i) {    return IntegralToString.intToBinaryString(i);}

IntegralToString.java

/** * The digits for every supported radix. */private static final char[] DIGITS = {        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',        'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',        'u', 'v', 'w', 'x', 'y', 'z'};public static String intToBinaryString(int i) {    int bufLen = 32;  // 整型是4个字节32位    char[] buf = new char[bufLen];    int cursor = bufLen;    do {        buf[--cursor] = DIGITS[i & 1];    }  while ((i >>>= 1) != 0);    return new String(cursor, bufLen - cursor, buf);}

运行过程

i=1i = 1, cursor = 32     do          i&1=1,buf[31] = DIGITS[1] = 1     while          i = 1>>>1 = 0,i == 0终止     00000000 00000000 00000000 00000001    -----------------------------------------     当i=2i = 2(10), cursor = 32     do          i&1=0,buf[31] = DIGITS[0] = 0     while          i = 2>>>1 = 1,i != 0成立     do          i&1=1,buf[30] = DIGITS[1] = 1     while          i = 1>>>1 = 0,i == 0终止     00000000 00000000 00000000 00000010

3.转换-Integer.valueOf

测试代码

public class test {    public static void main(String[] args) {        //十六进制转成十进制        System.out.println(Integer.valueOf("FFFF",16));        System.out.println(Integer.valueOf("-FFFF",16));        //八进制转成十进制        System.out.println(Integer.valueOf("776",8));        System.out.println(Integer.valueOf("-776",8));        //二进制转十进制        System.out.println(Integer.valueOf("0101",2));        System.out.println(Integer.valueOf("-0101",2));    }}

测试结果

65535-65535510-5105-5

源码

Integer.java

方法:valueOf

/**  * Parses the specified string as a signed integer value using the specified radix.  * 将制定的字符串转换为有符号的整数,参考指定的基数  * @param string  the string representation of an integer value.  * 字符串表示的整型值  * @param radix   the radix to use when parsing.  * 转换时指定基数,比如2代表2进制,8代表8进制,16代表16进制  * @return an {@code Integer} instance containing the integer value  *         represented by {@code string} using {@code radix}.  * 整形值被转换为指定的基数的字符串  * @throws NumberFormatException  *             if {@code string} cannot be parsed as an integer value, or  *             {@code radix < Character.MIN_RADIX ||  *             radix > Character.MAX_RADIX}.  * string不是整形值;radix< Character.MIN_RADIX或radix > Character.MAX_RADIX都会报转换异常  * @see #parseInt(String, int)  */ public static Integer valueOf(String string, int radix) throws NumberFormatException {     return valueOf(parseInt(string, radix)); }

方法:parseInt

/** * The minimum radix used for conversions between characters and integers. */public static final int MIN_RADIX = 2;/** * The maximum radix used for conversions between characters(字符) and integers.(整型) */public static final int MAX_RADIX = 36;/**  * Parses the specified string as a signed integer value using the specified radix.   * The ASCII characters \u002d ('-') and \u002b ('+') are recognized as the minus and plus signs.  * ASCII字符"-"和"+"被作为正负号  */ public static int parseInt(String string, int radix) throws NumberFormatException {     if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {         throw new NumberFormatException("Invalid radix: " + radix);     }     if (string == null || string.isEmpty()) {         throw invalidInt(string);//返回的是一个NumberFormatException异常     }     char firstChar = string.charAt(0);     //如果字符串以'-'或'+'开头,则firstDigitIndex = 1作为后续操作的标识     int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;     //字符串只有'-'或'+'抛异常     if (firstDigitIndex == string.length()) {         throw invalidInt(string);     }     return parse(string, firstDigitIndex, radix, firstChar == '-'); }

方法:parse

/** * Constant for the minimum {@code int} value, -2<sup>31</sup>. */public static final int MIN_VALUE = 0x80000000;private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {    int max = Integer.MIN_VALUE / radix;    int result = 0;    int length = string.length();    while (offset < length) {        int digit = Character.digit(string.charAt(offset++), radix);        if (digit == -1) {            throw invalidInt(string);        }        if (max > result) {            throw invalidInt(string);        }        int next = result * radix - digit;        if (next > result) {            throw invalidInt(string);        }        result = next;    }    //negative以'-'开头则为true    if (!negative) {//以'+'开头        result = -result;        if (result < 0) {            throw invalidInt(string);        }    }    return result;}

Character.java
方法:digit

public static int digit(char c, int radix) {     return digit((int) c, radix);}/** * Convenience method to determine the value of the character * {@code codePoint} in the supplied radix. The value of {@code radix} must * be between MIN_RADIX and MAX_RADIX. * 基于radix来确定codePoint指定的字符,radix必须在MIN_RADIX与MAX_RADIX之间 * @param codePoint  the character, including supplementary characters. * @return if {@code radix} lies between {@link #MIN_RADIX} and *         {@link #MAX_RADIX} then the value of the character in the radix; *         -1 otherwise. */public static int digit(int codePoint, int radix) {//1,2    //在最大与最小之间,否则返回-1    if (radix < MIN_RADIX || radix > MAX_RADIX) {        return -1;    }    if (codePoint < 128) {        // Optimized for ASCII        int result = -1;        if ('0' <= codePoint && codePoint <= '9') {            result = codePoint - '0';        } else if ('a' <= codePoint && codePoint <= 'z') {            result = 10 + (codePoint - 'a');        } else if ('A' <= codePoint && codePoint <= 'Z') {            result = 10 + (codePoint - 'A');        }        return result < radix ? result : -1;    }    //当前类的native方法    return digitImpl(codePoint, radix);}private static native int digitImpl(int codePoint, int radix);

运行过程

Integer.valueOf("11",2)//string, radix              parseInt("11", 2)//string, radixparse("11",0,2,false)//string, offset, radix, negativewhile(offset < string.length){    0 < 2成立    拿二进制的第11(从左到右)    Character.digit('1',2)//string.charAt(offset++), radix    Character.digit(49,2),return 1//(int) c, radix    digit('1',2),return 1    next = 0*2-1=-1//result * radix - digit    result = -1    拿二进制的第21(从左到右)     Character.digit('1',2)//string.charAt(offset++), radix    Character.digit(49,2),return 1//(int) c, radix    digit('1',2),return 1    next = -1*2 -1 = -3    result = -3 }//negative以'-'开头则为trueif (!negative) {    result = -result = 3;}return result = 3;
0 0
原创粉丝点击