在Java中把十进制(基数10)转换为十六进制(基数16)。

问题描述 投票:-1回答:1

我的问题是关于Java的。

我如何在Java中用Java 7将十进制(Base 10)转换为十六进制(Base 16)?

当我在C#中使用Convert.FromBase64String(str)这个方法时,用String "BQoPFBke "得到的结果是:05-0A-0F-14-19-1E。

但是当我在Java中使用Base64.Decoder.decode(str)方法来处理同一个字符串时,我得到了这样的结果。[5, 10, 15, 20, 25, 30]

我试着用decima2hex(15)将十进制转换为十六进制。

public static String decimal2hex(int d) {
    String digits = "0123456789ABCDEF";
    if (d <= 0) return "0";
    int base = 16;   // flexible to change in any base under 16
    String hex = "";
    while (d > 0) {
        int digit = d % base;              // rightmost digit
        hex = digits.charAt(digit) + hex;  // string concatenation
        d = d / base;
    }
    return hex;
}

但当我使用decima2hex(15)时,该方法只返回。F. 但我需要得到: 0F.

如何实现这个目标?

java c# hex decimal
1个回答
0
投票

使用 Integer.toHexString字符串.格式

public class Main {
    public static void main(String[] args) {
        // Test hexadecimal representation of integers from 0 to 15
        for (int i = 0; i < 16; i++) {
            System.out.print(decimal2Hex(i) + " ");
        }
    }

    public static String decimal2Hex(int d) {
        return String.format("%2s", Integer.toHexString(d)).toUpperCase().replace(' ', '0');
    }
}

输出。

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 

0
投票

请用这个试试

hex = hex.length() <=1 ? String.format("0%s",hex) : hex 。

完成Prog的输入和输出

public class App
{


    public static String decimal2hex(int d)
    {
        String digits = "0123456789ABCDEF";
        if (d <= 0) return "0";
        int base = 16;   // flexible to change in any base under 16
        String hex = "";
        while (d > 0)
        {
            int digit = d % base;              // rightmost digit
            hex = digits.charAt(digit) + hex;  // string concatenation
            d = d / base;
        }
        hex = hex.length() <= 1 ? String.format("0%s", hex) : hex;

        return hex;
    }

    public static void main(String[] args)
    {

        int[] nos = {5, 10, 15, 20, 25, 30};
        System.out.println("I/P");
        Arrays.stream(nos).forEach(System.out::println);
        System.out.println("O/P");
        Arrays.stream(nos).forEach(i ->
        {
            System.out.println(decimal2hex(i));
        });
    }

上述程序的输出

I/P
5
10
15
20
25
30
O/P
05
0A
0F
14
19
1E
© www.soinside.com 2019 - 2024. All rights reserved.