Java Hex Calculate toHex(byte[] data)

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

Description

Return a hex representation of the byte array

License

BSD License

Parameter

Parameter Description
data The data to transform.

Return

A hex representation of the data.

Declaration

public static String toHex(byte[] data) 

Method Source Code

//package com.java2s;
/**//from   w  w w .  j  a  v  a  2  s  .c o  m
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */

public class Main {
    /**
     * Return a hex representation of the byte array
     * 
     * @param data
     *            The data to transform.
     * @return A hex representation of the data.
     */
    public static String toHex(byte[] data) {
        if ((data == null) || (data.length == 0)) {
            return null;
        }

        StringBuffer result = new StringBuffer();

        // This is far from the most efficient way to do things...
        for (int i = 0; i < data.length; i++) {
            int low = (int) (data[i] & 0x0F);
            int high = (int) (data[i] & 0xF0);

            result.append(Integer.toHexString(high).substring(0, 1));
            result.append(Integer.toHexString(low));
        }

        return result.toString();
    }
}

Related

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