【Java】十进制和十六进制的转换

【代码】

package test;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test3 {
    public static void main(String[] args) {
        // 取当前时间戳
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
        LocalDateTime now=LocalDateTime.now();
        String str=formatter.format(now);
        // 以时间戳来生成一个大数字(字符串类型)
        System.out.println(str);
        
        //时间戳转long
        long num=Long.parseLong(str);
        
        // long转十六进制数方式一
        String hex1= Long.toHexString(num);
        System.out.println(hex1);
        
        // long转十六进制数方式二(小写)
        String hex2=String.format("%08x", num);
        System.out.println(hex2);
        
        // long转十六进制数方式二(大写)
        String hex3=String.format("%08X", num);
        System.out.println(hex3);
        
        // 十六进制数还原至十进制
        BigInteger l=new BigInteger(hex1, 16);
        System.out.println(l);
    }
}

输出:

20211226061056
1261caf32900
1261caf32900
1261CAF32900
20211226061056

END

原文地址:https://www.cnblogs.com/heyang78/p/15733623.html