欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

三种实现Java将十进制转为十六进制的方法

最编程 2024-01-13 08:06:59
...

第一种方法:

  Integer.toHexString( int i );

Integer.toString(int it,int radix)

其中Integer.toString(int i, int radix)包括Integer中的toBinaryString(int i)、toOctalString(int i)、toHexString(int i)。

第二种方法: 

      private static String decimalToHex(int decimal) {
        StringBuilder sb = new StringBuilder();
        do {
            int temp = decimal & 0xF;
            if (temp > 9) {
                sb.append((char) (temp - 10 + 'A'));
            } else {
                sb.append(temp);
            }
            decimal = decimal >>> 4;
        } while (decimal != 0);
        return sb.reverse().toString();
    }

 

第三种方法:

       public static String D2X(int d) {
        String x = "";
        if (d < 16) {
            x = change(d);
        } else {
            int c;
            int s = 0;
            int n = d;
            @SuppressWarnings("unused")
            int temp = d;
            while (n >= 16) {
                s++;
                n = n / 16;
            }
            String[] m = new String[s];
            int i = 0;
            do {
                c = d / 16;
                m[i++] = change(d % 16);
                d = c;
            } while (c >= 16);
            x = change(d);
            for (int j = m.length - 1; j >= 0; j--) {
                x += m[j];
            }
        }
        if (x.length() == 3) {
            x = "0" + x;
        } else if (x.length() == 2) {
            x = "00" + x;
        } else if (x.length() == 1) {
            x = "000" + x;
        }
        return x;
    }
 
    public static String change(int d) {
        String x = "";
        switch (d) {
        case 10:
            x = "A";
            break;
        case 11:
            x = "B";
            break;
        case 12:
            x = "C";
            break;
        case 13:
            x = "D";
            break;
        case 14:
            x = "E";
            break;
        case 15:
            x = "F";
            break;
        default:
            x = String.valueOf(d);
            break;
        }
        return x;
    }

这三种方法,第一种和第二种表现相同,而第三种负数的时候不行。

推荐阅读