Java Convert via ByteBuffer toHexBytes(byte[] bytes)

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

Description

Converts the given bytes into a hexadecimal representation.

License

Apache License

Parameter

Parameter Description
bytes Source bytes

Return

Hexadecimal string

Declaration

public static String toHexBytes(byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*from www. j  a v  a  2 s.co m*/
 * Copyright (C) 2014 Dell, Inc.
 * 
 * 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.
 */

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    /**
     * The Charset object for the UTF-8 character set.
     */
    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
    private final static String hexChars = "0123456789ABCDEF";

    /**
     * Converts the given bytes into a hexadecimal representation.
     * 
     * @param bytes Source bytes
     * @return Hexadecimal string
     */
    public static String toHexBytes(byte[] bytes) {
        return toHexBytes(bytes, 0, bytes.length);
    }

    /**
     * Converts the given bytes into a hexadecimal representation. bytes[offset] through
     * bytes[offset + length - 1] are converted, although the given array's length is
     * never exceeded.
     *
     * @param offset    Index of first byte to convert.
     * @param length    Number of bytes to convert.
     * @param bytes     Source bytes.
     * @return          Hexadecimal string.
     */
    public static String toHexBytes(byte[] bytes, int offset, int length) {
        StringBuilder builder = new StringBuilder();
        for (int index = offset; index < bytes.length && index < (offset + length); index++) {
            byte b = bytes[index];
            int first = (b >> 4) & 15;
            int second = b & 15;
            builder.append(hexChars.charAt(first)).append(hexChars.charAt(second));
        }
        return builder.toString();
    }

    /**
     * Convert the given byte[] to a String using the {@link #UTF8_CHARSET} decoder. This
     * is the inverse of {@link #toBytes(String)}. As with that method, null begets null.
     *
     * @param bytes A byte[] representing a String value.
     * @return      The decoded String value, or null if null is given.
     */
    public static String toString(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        //optimization for ASCII string
        String ascii = toAsciiString(bytes);
        if (ascii != null)
            return ascii;

        return new String(bytes, UTF8_CHARSET);
    }

    /**
     * Extract the byte[] within the given ByteBuffer and decode into a String using UTF-8.
     * This method calls {@link #copyBytes(ByteBuffer)}, which examines the ByteBuffer
     * without side-effects, therefore allowing it to be read again.
     * 
     * @param bytes ByteBuffer object.
     * @return      Internal byte[] value converted to a String using UTF-8.
     */
    public static String toString(ByteBuffer bytes) {
        return toString(copyBytes(bytes));
    }

    /**
     * Convert the a subset of given byte[] starting at index 'offset' for 'length' bytes
     * to a String using the reverse process used by {@link #toBytes(String)}. As with
     * that method, null begets null.
     *
     * @param bytes     Byte[] to convert.
     * @param offset    Index of first byte to convert.
     * @param length    Number of bytes to convert.
     * @return          Decoded string, or null if null is given.
     */
    public static String toString(byte[] bytes, int offset, int length) {
        if (bytes == null) {
            return null;
        }
        //optimization for ASCII string
        String ascii = toAsciiString(bytes, offset, length);
        if (ascii != null)
            return ascii;

        return new String(bytes, offset, length, UTF8_CHARSET);
    }

    private static String toAsciiString(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] < 0)
                return null;
        }
        char[] chars = new char[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            chars[i] = (char) bytes[i];
        }
        return new String(chars);
    }

    private static String toAsciiString(byte[] bytes, int offset, int length) {
        for (int i = 0; i < length; i++) {
            if (bytes[offset + i] < 0)
                return null;
        }
        char[] chars = new char[length];
        for (int i = 0; i < length; i++) {
            chars[i] = (char) bytes[offset + i];
        }
        return new String(chars);
    }

    /**
     * Extract the bytes in the given ByteBuffer and return it as a byte[] without
     * affecting the mark, position, or limit of the given buffer. This method should be
     * used instead of {@link #getBytes(ByteBuffer)} when the ByteBuffer might be re-read
     * again.
     *
     * @param   bytes   ByteBuffer.
     * @return          Contents between 'position' and 'limit' (aka 'remaining') as a
     *                  byte[]. Parameter object is unaffected.
     */
    public static byte[] copyBytes(ByteBuffer bytes) {
        ByteBuffer copy = bytes.duplicate();
        byte[] result = new byte[copy.remaining()]; // bytes between position and limit
        copy.get(result);
        return result;
    }
}

Related

  1. toFloatArray(int[] intArray)
  2. toFloatBytes(List datas)
  3. toGuidBytes(UUID theUuid)
  4. toGuidString(UUID uuid)
  5. toHex(byte[] bytes)
  6. toHexString(Number n)
  7. toInt(byte[] bytes)
  8. toInt(byte[] data)
  9. toInt(byte[] value)