Skip to content
Advertisement

Convert Decimal (Base 10) to Hexadecimal (Base 16) in Java

My question is about Java.

How can I convert Decimal (Base 10) to Hexadecimal (Base 16) in Java with Java 7?

When I use in C# the method Convert.FromBase64String(str) with String “BQoPFBke” i get the result: 05-0A-0F-14-19-1E

But when I use in Java the method Base64.Decoder.decode(str) with the same String I get the result: [5, 10, 15, 20, 25, 30]

I tryed to convert decimal to hexadecial with:

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;
}

but when i use for example decima2hex(15) the method returns only: F. But I need to get: 0F.

How can achieve this?

Advertisement

Answer

Use Integer.toHexString and String.format

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');
    }
}

Output:

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement