我要写一个程序将输入从Octal转换为Binary或Hex但是我不能使用预先编写的API例程来为我做转换。我认为最好的办法是对它们进行逆向工程,看看它们是如何起作用的。有没有人知道可以提供该信息或其他建议的来源?谢谢!
答案 0 :(得分:0)
您需要从基础开始,即将十进制数转换为二进制数。这个过程非常简单。然后,您可以继续前进,因为该过程类似。
正如其他人已经指出的那样,源代码与jdk捆绑在一起。
答案 1 :(得分:0)
如果你下载了intelliJ,那么你可以控制点击进入任何一个类。
此外,只需尝试谷歌搜索“java lang Integer的源代码”
我做了,然后提出来了:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java
这基本上是你用JDK做的(正如有人指出的那样):
String octalNo="037";
System.out.println(Integer.toHexString(Integer.parseInt(octalNo, 8)));
为了好玩,我做了八进制问题:
int octal = 037;
System.out.println(octalToHexString(octal));
int octal = 037;
System.out.println(octalToHexString(octal));
}
public static String octalToHexString(int octal) {
final char[] hex = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'A' , 'B' ,
'C' , 'D' , 'E' , 'F'
};
int val = octal;
int radix = 0;
int mask = 0;
StringBuilder builder = new StringBuilder("0x");
if (val==0) {
return "0x" + 0;
}
while (val != 0) {
radix = 1 << 4;
mask = radix - 1;
builder.insert(2, hex[val & mask]);
val >>>= 4;
}
return builder.toString();
}
以上效率不高。 :)
以下是来自JDK for int:
的解析器public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}