Java Hex Calculate toHexString(final byte[] b)

Here you can find the source of toHexString(final byte[] b)

Description

Converts a byte array to a hex string representing it.

License

Apache License

Parameter

Parameter Description
b the byte array to convert

Return

the hex representation of b

Declaration

public static String toHexString(final byte[] b) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  w  w  w . ja v  a  2s .  co  m*/
     * The hex digits used to build a hex string representation of a byte array.
     */
    public static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Converts a byte array to a hex string representing it. The hex digits are
     * lower case.
     * 
     * @param b the byte array to convert
     * @return the hex representation of b
     */
    public static String toHexString(final byte[] b) {
        final StringBuilder sb = new StringBuilder();

        for (final byte element : b) {
            sb.append(hexChar[(element & 0xf0) >>> 4]);
            sb.append(hexChar[element & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * Extends or truncate string to length if necessary and add to the string
     * builder.
     * 
     * @param sb
     * @param str
     * @param length
     */
    public static void append(final StringBuilder sb, final String str, final int length) {
        assert sb != null;
        if (str == null) {
            for (int i = 0; i < length; i++) {
                sb.append(' ');
            }
        } else {
            final int sl = str.length();
            if (sl < length) {
                sb.append(str);
                for (int i = sl; i < length; i++) {
                    sb.append(' ');
                }
            } else {
                sb.append(str.subSequence(0, length));
            }
        }

    }
}

Related

  1. toHexString(final byte b)
  2. toHexString(final byte hex)
  3. toHexString(final byte value)
  4. toHexString(final byte[] arr)
  5. toHexString(final byte[] array)
  6. toHexString(final byte[] bs)
  7. toHexString(final byte[] bs, final char[] myDigits)
  8. toHexString(final byte[] buffer)
  9. toHexString(final byte[] bytes)