Java教程

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

我们可以使用 Integer.toHexString()方法或自定义逻辑在Java中将 十进制转换为十六进制

Java十进制到十六进制的转换: Integer.toHexString()

Integer.toHexString()方法将十进制转换为十六进制。 toHexString()方法的 签名如下所示:
public static String toHexString(int decimal)
让我们看看在Java中将十进制转换为二进制的简单示例。
public class DecimalToHexExample1{
    public static void main(String args[]){
        System.out.println(Integer.toHexString(10));
        System.out.println(Integer.toHexString(15));
        System.out.println(Integer.toHexString(289));
    }
}
输出:
af121

Java十进制转换为十六进制: 自定义逻辑

我们可以使用自定义逻辑将 十进制转换为Java中的十六进制
public class DecimalToHexExample2{
    public static String toHex(int decimal){
        int rem;
        String hex="";
        char hexchars[]={
        '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}
        ;
        while(decimal>0) {
            rem=decimal%16;
            hex=hexchars[rem]+hex;
            decimal=decimal/16;
        }
        return hex;
    }
    public static void main(String args[]){
        System.out.println("Hexadecimal of 10 is: "+toHex(10));
        System.out.println("Hexadecimal of 15 is: "+toHex(15));
        System.out.println("Hexadecimal of 289 is: "+toHex(289));
    }
}
输出:
Hexadecimal of 10 is: AHexadecimal of 15 is: FHexadecimal of 289 is: 121
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4