Java Byte Array to Hex String bytesToHexChars(byte[] bytes)

Here you can find the source of bytesToHexChars(byte[] bytes)

Description

Convert binary data into a sequence of pairs of hexadecimal character values.

License

Apache License

Parameter

Parameter Description
bytes Bytes to convert to a hex string.

Exception

Parameter Description
NullPointerException The given array of bytes is <code>null</code>.

Return

Hex string representation of the given bytes.

Declaration

public final static char[] bytesToHexChars(byte[] bytes) throws NullPointerException 

Method Source Code

//package com.java2s;
/*//  ww  w .  j  av  a2  s .  co m
 * Copyright 2016 Richard Cartwright
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /** <p>Hexidecimal character array used for encoding binary data.</p> */
    private final static char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**
     * <p>Convert binary data into a sequence of pairs of hexadecimal character values.</p>
     *
     * @param bytes Bytes to convert to a hex string.
     * 
     * @return Hex string representation of the given bytes.
     * 
     * @throws NullPointerException The given array of bytes is <code>null</code>.
     * 
     * @see #hexStringToBytes(String)
     */
    public final static char[] bytesToHexChars(byte[] bytes) throws NullPointerException {

        if (bytes == null)
            throw new NullPointerException("Cannot convert a null byte array to hex string.");

        char[] chars = new char[bytes.length * 2];

        int charCounter = 0;
        for (int x = 0; x < bytes.length; x++) {
            chars[charCounter++] = hexChars[(bytes[x] >>> 4) & 0x0f];
            chars[charCounter++] = hexChars[bytes[x] & 0x0f];
        }

        return chars;
    }
}

Related

  1. bytes2hexStr(byte[] arr, int len)
  2. bytes_to_hex(byte[] b)
  3. bytes_to_hex(byte[] bytes)
  4. bytesToHexAppend(byte[] bs, int off, int length, StringBuffer sb)
  5. bytesToHexChars(byte[] bytes)
  6. bytesToHexChars(byte[] bytes)
  7. bytesToHexChecksum(byte[] byteArr)
  8. bytesToHexDelimeter(byte[] data, String delimeter)