Java Convert via ByteBuffer toHex(byte[] bytes)

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

Description

Returns hex-digit (lower case) string.

License

Open Source License

Declaration

public static String toHex(byte[] bytes) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

public class Main {
    /**/*w w w.ja  v a2  s . c  o  m*/
     * Returns hex-digit (lower case) string.
     */
    public static String toHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            int value = (int) bytes[i] & 0xff;
            if (value < 0x10) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(value));
        }
        return buf.toString();
    }

    /**
     * convert a ByteBuffer to a String
     * ByteBuffer is reset to its original state.
     */
    static public String toString(ByteBuffer value, String charsetName) {
        String result = null;
        try {
            result = new String(toBytes(value), charsetName);
        } catch (Exception e) {
        }
        return result;
    }

    static public String toString(int value, int radix, int minChars) {
        String result = Integer.toString(value, radix);
        int leadZeroes = minChars - result.length();
        if (leadZeroes > 0) {
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < leadZeroes; i++) {
                buf.append("0");
            }
            buf.append(result);
            result = buf.toString();
        }
        return result;
    }

    /**
     * Convert a ByteBuffer to a byte[]
     * ByteBuffer is reset to its original state.
     */
    static public byte[] toBytes(ByteBuffer value) {
        byte[] result = null;
        if (value != null && value.remaining() > 0) {
            result = new byte[value.remaining()];
            value.mark();
            value.get(result);
            value.reset();
        }
        return result;
    }
}

Related

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