您的位置:首页 > 编程语言 > Java开发

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

2016-09-21 17:26 267 查看

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进制10
16进制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)=1
Integer.toBinaryString(012)=1010
Integer.toBinaryString(10)=1010
Integer.toBinaryString(0xa)=1010
Integer.toOctalString(0x12)=22
Integer.toOctalString(18)=22
Integer.toHexString(012)=a
Integer.toHexString(10)=a


源码

toBinaryString、toOctalString、toHexStrin
4000
g都类似,则以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=1时
i = 1, cursor = 32
do
i&1=1,buf[31] = DIGITS[1] = 1
while
i = 1>>>1 = 0,i == 0终止
00000000 00000000 00000000 00000001
-----------------------------------------
当i=2时
i = 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
-65535
510
-510
5
-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) {
retu
bf70
rn -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, radix
parse("11",0,2,false)//string, offset, radix, negative
while(offset < string.length){
0 < 2成立
拿二进制的第1位1(从左到右)
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
拿二进制的第2位1(从左到右)
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以'-'开头则为true
if (!negative) {
result = -result = 3;
}
return result = 3;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐