Java Hex Calculate toHex(StringBuffer buf, long value, int width)

Here you can find the source of toHex(StringBuffer buf, long value, int width)

Description

to Hex

License

Open Source License

Declaration

public static void toHex(StringBuffer buf, long value, int width) 

Method Source Code

//package com.java2s;

public class Main {
    public static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**//from   w ww . j a  va2  s  .com
     * The <code>toHex()</code> converts the specified long value into a hexadecimal string of the given with.
     * The value will be padded on the left with zero values to achieve the desired with.
     *
     * @param value the long value to convert to a string
     * @param width the desired length of the string
     * @return a hexadecimal string representation of the given value, padded on the left with zeroes to the
     *         length specified
     */
    public static String toHex(long value, int width) {
        char result[] = new char[width];
        return convertToHex(value, width, 0, result);
    }

    public static void toHex(StringBuffer buf, long value, int width) {
        if (value > (long) 1 << width * 4) {
            buf.append(Long.toHexString(value).toUpperCase());
            return;
        }

        for (int cntr = width - 1; cntr >= 0; cntr--)
            buf.append(HEX_CHARS[(int) (value >> (cntr * 4)) & 0xf]);
    }

    private static String convertToHex(long value, int width, int start, char[] result) {
        if (value > (long) 1 << width * 4)
            return Long.toHexString(value).toUpperCase();

        int i = start + width - 1;
        for (int cntr = 0; cntr < width; cntr++) {
            result[i - cntr] = HEX_CHARS[(int) (value >> (cntr * 4)) & 0xf];
        }

        return new String(result);
    }
}

Related

  1. toHex(String source)
  2. toHex(String str)
  3. toHex(String string)
  4. toHex(String txt)
  5. toHex(String val)
  6. toHex(StringBuilder s, byte b)
  7. toHex00String(int c)
  8. toHEX1(byte b)
  9. toHex16(int w)