Java Hex Calculate toHexString(int value, int len)

Here you can find the source of toHexString(int value, int len)

Description

Returns Hexadecimal String of specified number of digits padding with zeroes if necessary

License

Open Source License

Parameter

Parameter Description
value integer to convert
len length of result

Return

String

Declaration

public static String toHexString(int value, int len) 

Method Source Code

//package com.java2s;
/*//from   w ww. ja v  a 2  s . c  o m
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    private static final int LOWERCASE_ASCII_MIN = 65;
    private static final int NUMBER_ASCII_MIN = 48;

    /**
     * Returns Hexadecimal String of specified number of digits
     * padding with zeroes if necessary
     * @param value integer to convert
     * @param len length of result
     * @return String 
     */
    public static String toHexString(int value, int len) {
        String retval = "";

        // we need to shift in groups of 4-bits this time
        for (int i = (len - 1) * 4; i >= 0; i -= 4) {
            // shift rgb 4 bits at a time, mask
            int j = value >> i & 0xF;

            // if 10 - 15 we need a - f
            if (j > 9) {
                j += LOWERCASE_ASCII_MIN - 10; // ASCII characters a - f

            } else {
                j += NUMBER_ASCII_MIN; // ASCII characters 0 - 9
            }
            retval += (char) j; // convert ASCII int value to char
        }
        return retval;
    }
}

Related

  1. toHexString(int n)
  2. toHexString(int number, int digit)
  3. toHexString(int r, int g, int b, int a)
  4. toHexString(int val)
  5. toHexString(int val, int minLength)
  6. ToHexString(int value, int length)
  7. toHexString(int value, int minLength)
  8. toHexString(int value, int numDigits)
  9. toHexString(int[] data)