Java Hex Calculate toHexByteArray(final byte[] buffer)

Here you can find the source of toHexByteArray(final byte[] buffer)

Description

Generate a byte array that is a hex representation of a given byte array.

License

Apache License

Parameter

Parameter Description
buffer to convert to a hex representation

Return

new byte array that is hex representation (in Big Endian) of the passed array

Declaration

public static byte[] toHexByteArray(final byte[] buffer) 

Method Source Code

//package com.java2s;
/*//from w  ww. j av  a  2 s. com
 * Copyright 2014 Real Logic Ltd.
 *
 * 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 {
    private static final byte[] HEX_DIGIT_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
            'd', 'e', 'f' };

    /**
     * Generate a byte array that is a hex representation of a given byte array.
     *
     * @param buffer to convert to a hex representation
     * @return new byte array that is hex representation (in Big Endian) of the passed array
     */
    public static byte[] toHexByteArray(final byte[] buffer) {
        return toHexByteArray(buffer, 0, buffer.length);
    }

    /**
     * Generate a byte array that is a hex representation of a given byte array.
     *
     * @param buffer to convert to a hex representation
     * @param offset the offset into the buffer
     * @param length the number of bytes to convert
     * @return new byte array that is hex representation (in Big Endian) of the passed array
     */
    public static byte[] toHexByteArray(final byte[] buffer, int offset, int length) {
        final byte[] outputBuffer = new byte[length << 1];

        for (int i = 0; i < (length << 1); i += 2) {
            final byte b = buffer[offset + (i >> 1)];

            outputBuffer[i] = HEX_DIGIT_TABLE[(b >> 4) & 0x0F];
            outputBuffer[i + 1] = HEX_DIGIT_TABLE[b & 0x0F];
        }

        return outputBuffer;
    }
}

Related

  1. toHexByte(byte b)
  2. toHexByte(byte b, StringBuffer sb)
  3. toHexByte(final char ch1, final char ch2)
  4. toHexByte(int bite)
  5. toHexByte(int i)
  6. toHexBytes(byte[] bytes)
  7. toHexBytes(byte[] data)
  8. toHexBytes(byte[] toBeConverted)
  9. toHexChar(byte[] bArray)