Java Hex Calculate toHexString(int decimal, int stringLength)

Here you can find the source of toHexString(int decimal, int stringLength)

Description

Converts a decimal value to a hexadecimal string represention of the specified length.

License

BSD License

Parameter

Parameter Description
decimal A decimal value.
stringLength The length of the resulting string.

Declaration

public static String toHexString(int decimal, int stringLength) 

Method Source Code

//package com.java2s;
/*//from w w w.  j  a  va  2s. c  o m
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */

public class Main {
    /**
     * Converts a decimal value to a hexadecimal string represention
     * of the specified length.
     *
     * @param decimal A decimal value.
     * @param stringLength The length of the resulting string.
     */
    public static String toHexString(int decimal, int stringLength) {
        StringBuilder sb = new StringBuilder(stringLength);

        String hexVal = Integer.toHexString(decimal).toUpperCase();

        // insert zeros if hexVal has less than stringLength characters:
        int nofZeros = stringLength - hexVal.length();
        for (int i = 0; i < nofZeros; i++) {
            sb.append('0');
        }

        sb.append(hexVal);

        return sb.toString();
    }
}

Related

  1. toHexString(final long num, final char paddingChar, int min, int max)
  2. toHexString(int b)
  3. toHexString(int b)
  4. toHexString(int bits, int value)
  5. toHexString(int decimal, int stringLength)
  6. toHexString(int i)
  7. toHexString(int i)
  8. toHexString(int i)
  9. toHexString(int i)