0

对于作业,我必须编写一个程序,该程序将接收 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 位可以容纳的最高值,任何超过此值的都将是溢出,因此这意味着它应该是负数。从这里我不知道该怎么做。任何指针或提示将不胜感激。如果没有办法在数学上做到这一点,我觉得我将不得不将十六进制转换为二进制,然后对其执行二进制补码,但我又不知道从哪里开始。

提前致谢

4

2 回答 2

3

如果代码中的数字为负数 (> 2147483647),只需2^32从中减去 (4294967296)。然后打印出来。

if (ans > 2147483647) {
        System.out.println(ans - 4294967296L);
   } else {
        System.out.println(ans);
   }
于 2011-09-28T01:56:29.680 回答
2

在 32 位 2 的补码二进制表示中,负数的值恰好比无符号表示中相同位模式的值小 2 ^ 32。您已经确定该数字可能为负数;剩下要做的就是减去 2 ^ 32。

当然,2 ^ 32(十进制为 4294967296,十六进制为 0x100000000)是 Java 的“int”类型无法表示的值,因此您需要使用“long”:

if (ans > 2147483647) {
    // System.out.println("is negative");
    ans = ans - 0x100000000L;
    System.out.println(ans);
} else {
于 2011-09-28T02:01:59.580 回答