Convert an int into a hex string. - Java java.lang

Java examples for java.lang:Hex

Description

Convert an int into a hex string.

Demo Code


//package com.java2s;

public class Main {
    /**//from  w  w w. j a  v a  2 s  . c o m
     * Convert an int into a hex string.
     *
     * @param decimal the integer
     * @return the formatted hex string
     */
    public static String convertToHex(int decimal) {
        String x = Integer.toHexString(decimal);
        while (x.length() < 4) {
            x = "0" + x;
        }
        x = "0x" + x;
        return x;
    }

    /**
     * Convert a long into a hex string.
     *
     * @param decimal the long
     * @return the formatted hex string
     */
    public static String convertToHex(long decimal) {
        String x = Long.toHexString(decimal);
        if (x.length() <= 2) {
            while (x.length() < 2) {
                x = "0" + x;
            }
        } else if (x.length() <= 4) {
            while (x.length() < 4) {
                x = "0" + x;
            }
        } else if (x.length() <= 6) {
            while (x.length() < 6) {
                x = "0" + x;
            }
        } else {
            while (x.length() < 8) {
                x = "0" + x;
            }
        }
        x = "0x" + x;
        return x;
    }
}

Related Tutorials