首页 > 代码库 > java十进制转十六进制

java十进制转十六进制

package com.ds.detect;

import java.util.Scanner;

public class ToHEX{
	
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请出入一个十进制数");
        int num = sc.nextInt();
        toHex(num);
        System.out.println("输入数字的16进制结果是:"+Integer.toHexString(num));// java自带的转换十六进制方法
        sc.close();
    }
 
    public static void toHex(int num) {
        if (num == 0) {
            System.out.println(‘0‘);
            return;
        }
        char[] chs = {‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘,‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘};
        char[] arr = new char[8];
        int pos = arr.length;
        while (num != 0) {
            arr[--pos] = chs[num & 15];
            num = num >>> 4;
        }
        for (int i = pos; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
    }
}

  

java十进制转十六进制