Here you can find the source of toHexFromBytes(final byte[] bytes)
Parameter | Description |
---|---|
bytes | byte[] the bytes to be converted |
public static String toHexFromBytes(final byte[] bytes)
//package com.java2s; //License from project: Open Source License public class Main { /** Allowable hex values */ private final static String[] hexSymbols = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public final static int BITS_PER_HEX_DIGIT = 4; /**//w w w . ja v a2s . com * Takes the given input and returns a String containing the hex representation of the bytes. * * @param bytes * byte[] the bytes to be converted * * @return String the hex conversion of the bytes (2 * bytes.length characters), and empty String if a null array is passed * */ public static String toHexFromBytes(final byte[] bytes) { if (bytes == null || bytes.length == 0) { return (""); } // there are 2 hex digits per byte StringBuilder hexBuffer = new StringBuilder(bytes.length * 2); // for each byte, convert it to hex and append it to the buffer for (int i = 0; i < bytes.length; i++) { hexBuffer.append(toHexFromByte(bytes[i])); } return (hexBuffer.toString()); } /** * Takes the given input and returns a String containing the hex representation of the bytes. * * @param bytes * byte[] the bytes to be converted * @param offset starting offset into the byte array * @param length number of bytes to convert * * @return String the hex conversion of the bytes (2 * length characters), and empty String if a null array is passed * */ public static String toHexFromBytes(final byte[] bytes, int offset, int length) { if (bytes == null || bytes.length == 0) { return (""); } if (offset > bytes.length || offset + length > bytes.length) { throw new IllegalArgumentException("Offset/length combination exceeds length of input byte array"); } // there are 2 hex digits per byte StringBuilder hexBuffer = new StringBuilder(length * 2); // for each byte, convert it to hex and append it to the buffer for (int i = offset; i < offset + length; i++) { hexBuffer.append(toHexFromByte(bytes[i])); } return (hexBuffer.toString()); } /** * Takes the given input and returns a String containing the hex representation of the byte. * * @param b * byte the byte to be converted * * @return String the hex conversion of the byte (2 characters) */ public static String toHexFromByte(final byte b) { // need to and the shift result as java maintains the // sign bit and puts it back after the shift byte leftSymbol = (byte) ((b >>> BITS_PER_HEX_DIGIT) & 0x0f); byte rightSymbol = (byte) (b & 0x0f); return (hexSymbols[leftSymbol] + hexSymbols[rightSymbol]); } }