对于作业,我必须编写一个程序,该程序将接收 8 个字符串(十六进制),然后将其转换为以 10 为基数。我不允许使用任何外部类来执行此操作。我很确定我的工作正常......仅适用于正数。我的问题是如何显示负数。一个例子是 FFFFFFFA 应该打印为 -6 这是我到目前为止的代码
package hexconverter;
import java.util.*;
/**
*
* @author Steven
*/
public class Main {
Scanner scanner = new Scanner(System.in);
public void doWork() {
System.err.println("Please enter the internal representation: ");
String hex;
hex = scanner.next();
hex = hex.toUpperCase();
long count = 1;
long ans = 0;
for (int i = 7; i >= 0; i--) {
Character c = hex.charAt(i);
if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
int num = fixLetters(c);
ans = ans + (num * count);
count = count * 16;
} else {
String s = c.toString(c);
long num = Integer.parseInt(s);
ans = ans + (num * count);
count = count * 16;
}
}
if (ans > 2147483647) {
System.out.println("is negative");
} else {
System.out.println(ans);
}
}
public int fixLetters(Character c) {
if (c.equals('A')) {
return 10;
} else if (c.equals('B')) {
return 11;
} else if (c.equals('C')) {
return 12;
} else if (c.equals('D')) {
return 13;
} else if (c.equals('E')) {
return 14;
} else if (c.equals('F')) {
return 15;
} else {
return 0;
}
}
public static void main(String[] args) {
// TODO code application logic here
Main a = new Main();
a.doWork();
}
}
我认为我对负整数的测试是正确的……因为这是 32 位可以容纳的最高值,任何超过此值的都将是溢出,因此这意味着它应该是负数。从这里我不知道该怎么做。任何指针或提示将不胜感激。如果没有办法在数学上做到这一点,我觉得我将不得不将十六进制转换为二进制,然后对其执行二进制补码,但我又不知道从哪里开始。
提前致谢