Java 从十进制转换为十六进制

Java 从十进制转换为十六进制,java,algorithm,Java,Algorithm,我编写了一个java程序,该程序应该将1到256之间的小数转换为十六进制,但当我尝试使用256以上的小数时,问题就出现了,在这之后,我开始得到错误的结果。 以下是我的代码: public class Conversion { public static void main(String[] args) { System.out.printf("%s%14s", "Decimal", "Hexadecimal"); for(int i = 1; i <= 300; i+

我编写了一个java程序,该程序应该将1到256之间的小数转换为十六进制,但当我尝试使用256以上的小数时,问题就出现了,在这之后,我开始得到错误的结果。 以下是我的代码:

public class Conversion {

public static void main(String[] args) {

    System.out.printf("%s%14s", "Decimal", "Hexadecimal");

    for(int i = 1; i <= 300; i++) {
        System.out.printf("%7d          ", i);
        decimalToHex(i);
        System.out.println();
    }

}

private static void decimalToHex(int decimal) {
    int count;
    if(decimal >= 256) {
        count = 2;
    } else {
        count = 1;
    }
    for (int i = 1; i <= count; i++) {
        if(decimal >= 256) {
            returnHex(decimal / 256);
            decimal %= 256;
        }

        if(decimal >= 16) {
            returnHex(decimal / 16);
            decimal %= 16;
        }

        returnHex(decimal);

        decimal /= 16;
    }
}

private static void returnHex(int number) {
    switch(number) {
        case 15:
            System.out.print("F");
            break;
        case 14:
            System.out.print("E");
            break;
        case 13:
            System.out.print("D");
            break;
        case 12:
            System.out.print("C");
            break;
        case 11:
            System.out.print("B");
            break;
        case 10:
            System.out.print("A");
            break;
        default:
            System.out.printf("%d", number);
            break;
    }
}

}

注意:我刚刚开始学习java,如果可以的话,请尽量简单。谢谢

您应该使用此方法将十进制转换为十六进制

 int i = ...
 String hex = Integer.toHexString(i);
 System.out.println("Hex value is " + hex);
您可以在此链接上找到更多详细信息


使用Integer.toHexString(i)而不是您自己的

如果
十进制
小于比较值,您只是忘记了打印零值。当显式打印出这些零时,您也不再需要
count
变量:

private static void decimalToHex(int decimal) {
    if (decimal >= 256) {
        returnHex(decimal / 256);
        decimal %= 256;
    } else {
        System.out.print("0");
    }
    if (decimal >= 16) {
        returnHex(decimal / 16);
        decimal %= 16;
    } else {
        System.out.print("0");
    }
    returnHex(decimal);
    decimal /= 16;
}

当然,这也会改变小值的输出。它打印000001,

请尝试或使用以下内容调整代码:

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }


  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

来源:

首先,@Seelenvirtuose给出的答案简单易懂,我只想补充一下。 十六进制基数是16,所以您不需要担心任何其他数字(例如256),这里我将您的两种方法简化如下:

private static void decimalToHex(int num) {
        String output="";
        while(num!=0){
            output=returnHex(num%16)+output;
            num=num/16;
        }
        System.out.println(output);
}

private static String returnHex(int number) {
            switch(number) {
            case 15:
                return "F";
            case 14:
                return "E";
            case 13:
                return "D";
            case 12:
                return "C";
            case 11:
               return "B";
            case 10:
                return "A";
            default:
                return ""+number;
        }
}
我所做的就是使用基数16和循环,直到数字为0。 此代码基于您自己的实现。很容易理解。

因此,请参阅Virtuose postet一个适用于4095以下数字的良好解决方案。让我们更进一步:

主要问题(正如您可能已经注意到的)是,您需要预测最高数字的基值是多少。您有一个解决方案首先检查256,而不是16。Java可以为我们找到合适的价值:

private static void decimalToHex(int decimal) {
    // Hex is base-16; maxDigit will hold the factor by which the highest digit needs to be multiplied to get its value
    int maxDigit = 1;
    // the condition left of && is what we want, right is to notice overflow when dealing with e.g. Integer.MAX_VALUE as input
    while(maxDigit * 16 <= decimal && maxDigit > 0) {
        maxDigit *= 16;
    }
    if(maxDigit <= 0) {
        throw new IllegalArgumentException("Can not convert "+ decimal);
    }
    // The left-most digit is the highest, so we need to go from high to low
    for(int digit = maxDigit; digit > 0; digit /= 16) {
        printHex((decimal / digit) % 16);
    }
}

// as this function prints the digits let's call it "printHex"
private static void printHex(int number) {
    switch(number) {
        case 15:
            System.out.print("F");
            break;
        case 14:
            System.out.print("E");
            break;
        case 13:
            System.out.print("D");
            break;
        case 12:
            System.out.print("C");
            break;
        case 11:
            System.out.print("B");
            break;
        case 10:
            System.out.print("A");
            break;
        default:
            System.out.printf("%d", number);
            break;
    }
}

由于您在问题中提到您刚刚开始学习java,并且希望保持简单,因此我建议您通过下面的示例了解更多关于java中十进制到十六进制转换的信息


示例。

非常确定海报不需要预先制作的解决方案。通常,最好的解决方案是最简单的。您明确表示希望将其从1转换为256…那么,为什么您关心256之后的问题?您的代码似乎存在溢出问题。当超过256时,尝试使用long-as类型。你可以在@TheConstructor No上发布类似的问题,实际上codereview仅用于工作代码。这个问题是关于解决一个问题(非工作代码)。@Radiodef好的,很高兴知道!我觉得几乎可以工作了。顺便说一下,
int
不是十进制的。@kellymandem欢迎使用stackoverflow!如果你觉得这个答案很有用,你可能想“接受”它,这样每个人都会意识到你的问题已经解决了。@kellymandem要接受答案,请单击答案左上角的白色复选标记,就在答案评分的正下方。这也有助于其他与类似问题作斗争的人找到最有用的答案:)我认为这里的假设是,他想为练习做出自己的决定。
private static void decimalToHex(int decimal) {
    // Hex is base-16; maxDigit will hold the factor by which the highest digit needs to be multiplied to get its value
    int maxDigit = 1;
    // the condition left of && is what we want, right is to notice overflow when dealing with e.g. Integer.MAX_VALUE as input
    while(maxDigit * 16 <= decimal && maxDigit > 0) {
        maxDigit *= 16;
    }
    if(maxDigit <= 0) {
        throw new IllegalArgumentException("Can not convert "+ decimal);
    }
    // The left-most digit is the highest, so we need to go from high to low
    for(int digit = maxDigit; digit > 0; digit /= 16) {
        printHex((decimal / digit) % 16);
    }
}

// as this function prints the digits let's call it "printHex"
private static void printHex(int number) {
    switch(number) {
        case 15:
            System.out.print("F");
            break;
        case 14:
            System.out.print("E");
            break;
        case 13:
            System.out.print("D");
            break;
        case 12:
            System.out.print("C");
            break;
        case 11:
            System.out.print("B");
            break;
        case 10:
            System.out.print("A");
            break;
        default:
            System.out.printf("%d", number);
            break;
    }
}
private static void decimalToHex2(int decimal) {
    // We use a StringBuilder so we can generate the digits lowest first
    StringBuilder sb = new StringBuilder();
    while (decimal > 0) {
        sb.append(returnHex(decimal % 16));
        decimal = decimal / 16;
    }
    // Now we can reverse the sequence and are fine
    String hexString = sb.reverse().toString();
    System.out.print(hexString);
}

// as this function returns the digits let's call it "returnHex"
private static char returnHex(int number) {
    switch(number) {
        case 15:
            return 'F';
        case 14:
            return 'E';
        case 13:
            return 'D';
        case 12:
            return 'C';
        case 11:
            return 'B';
        case 10:
            return 'A';
        default:
            return (char) ('0' + number);
    }
}