Java Hex Calculate toHex(byte[] data)

Here you can find the source of toHex(byte[] data)

Description

Return the passed in byte array as a hex string.

License

Apache License

Parameter

Parameter Description
data the bytes to be converted.

Return

a hex representation of data.

Declaration

public static String toHex(byte[] data) 

Method Source Code

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

public class Main {
    private final static String DIGITS = "0123456789abcdef";

    /**/*ww  w. j a v  a 2 s . c o m*/
     * Return length many bytes of the passed in byte array as a hex string.
     *
     * @param data   the bytes to be converted.
     * @param length the number of bytes in the data block to be converted.
     * @return a hex representation of length bytes of data.
     */
    public static String toHex(byte[] data, int length) {
        StringBuilder buf = new StringBuilder();

        for (int i = 0; i != length; i++) {
            int v = data[i] & 0xff;

            buf.append(DIGITS.charAt(v >> 4));
            buf.append(DIGITS.charAt(v & 0xf));
        }

        return buf.toString();
    }

    /**
     * Return the passed in byte array as a hex string.
     *
     * @param data the bytes to be converted.
     * @return a hex representation of data.
     */
    public static String toHex(byte[] data) {
        return toHex(data, data.length);
    }

    public static String toString(byte[] bytes, int length) {
        char[] chars = new char[length];
        for (int i = 0; i != chars.length; i++) {
            chars[i] = (char) (bytes[i] & 0xff);
        }
        return new String(chars);
    }
}

Related

  1. toHex(byte[] bytes)
  2. toHex(byte[] bytes)
  3. toHex(byte[] bytes)
  4. toHex(byte[] bytes)
  5. toHex(byte[] bytes, int maxlen)
  6. toHex(byte[] data)
  7. toHex(byte[] data)
  8. toHex(byte[] data)
  9. toHex(byte[] data)