Java - Write code to Convert a value to a hex string with a fixed number of digits.

Requirements

Write code to Convert a value to a hex string with a fixed number of digits.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        int value = 42;
        int digits = 2;
        System.out.println(intToHexString(value, digits));
    }/*www . j av a 2s .  c o m*/

    /** Converts a value to a hex string with a fixed number of digits. */
    public static String intToHexString(int value, int digits) {
        String result = Integer.toHexString(value);
        for (int i = result.length(); i < digits; i++) {
            result = "0" + result;
        }
        // trim result if needed
        if (result.length() > digits) {
            return result.substring(result.length() - digits);
        }
        return result;
    }
}