Java Byte Array to Hex bytesToHex(byte[] b, int offset, int length)

Here you can find the source of bytesToHex(byte[] b, int offset, int length)

Description

Converts a byte array to a hexadecimal string.

License

Open Source License

Parameter

Parameter Description
b the array to be converted.
offset the start offset within <code>b</code>.
length the number of bytes to convert.

Exception

Parameter Description
IllegalArgumentException if offset and length are misplaced

Return

A string representation of the byte array.

Declaration

public static String bytesToHex(byte[] b, int offset, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  ww  w  . j a  va 2s.  c o  m*/
     * Converts a byte array to a hexadecimal string.  Conversion starts at byte 
     * <code>offset</code> and continues for <code>length</code> bytes.
     * 
     * @param b      the array to be converted.
     * @param offset the start offset within <code>b</code>.
     * @param length the number of bytes to convert.
     * @return A string representation of the byte array.
     * @throws IllegalArgumentException if offset and length are misplaced
     */
    public static String bytesToHex(byte[] b, int offset, int length) {
        StringBuffer sb;
        String result;
        int i, top;

        top = offset + length;
        if (length < 0 || top > b.length)
            throw new IllegalArgumentException();

        sb = new StringBuffer();
        for (i = offset; i < top; i++) {
            sb.append(byteToHex(b[i]));
        }
        result = sb.toString();
        return result;
    }

    /**
     * Converts a byte array to a hexadecimal string.  
     * 
     * @param b      the array to be converted.
     * @return A string representation of the byte array.
     */
    public static String bytesToHex(byte[] b) {
        return bytesToHex(b, 0, b.length);
    }

    /** Returns a two char hexadecimal String representation of a single byte.
     * 
     * @param v integer with a byte value (-128 .. 255); other values get truncated
     * @return an absolute hex value representation (unsigned) of the input
     */
    public static String byteToHex(int v) {
        String hstr;
        hstr = Integer.toString(v & 0xff, 16);

        return hstr.length() == 1 ? "0" + hstr : hstr;
    }
}

Related

  1. bytesToHex(byte[] array)
  2. bytesToHex(byte[] b)
  3. bytesToHex(byte[] b)
  4. bytesToHex(byte[] b)
  5. bytesToHex(byte[] b)
  6. bytesToHex(byte[] binary)
  7. bytesToHex(byte[] bs, int off, int length)
  8. bytesToHex(byte[] bt)
  9. bytesToHex(byte[] buf)