Java ByteBuffer to Hex toHexString(ByteBuffer bb, boolean withSpaces)

Here you can find the source of toHexString(ByteBuffer bb, boolean withSpaces)

Description

to Hex String

License

Open Source License

Declaration

public static String toHexString(ByteBuffer bb, boolean withSpaces) 

Method Source Code


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

import java.nio.ByteBuffer;

public class Main {
    private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    public static String toHexString(byte b) {
        return toHexString(toByteArray(b), false);
    }//from  ww  w. j  ava  2 s .  co  m

    public static String toHexString(byte[] array, boolean withSpaces) {
        return toHexString(array, 0, array.length, withSpaces);
    }

    public static String toHexString(ByteBuffer bb, boolean withSpaces) {
        byte[] data = new byte[bb.remaining()];
        int position = bb.position();
        bb.get(data);
        bb.position(position);
        return toHexString(data, withSpaces);
    }

    public static String toHexString(byte[] array, int offset, int length, boolean withSpaces) {

        if (length == 0) {
            return "";
        }
        if (withSpaces) {
            char[] buf = new char[length * 2 + length - 1];

            int bufIndex = 0;
            for (int i = offset; i < offset + length; i++) {
                if (i > offset) {
                    buf[bufIndex++] = ' ';
                }
                byte b = array[i];
                buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
                buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
            }
            return new String(buf);
        } else {
            char[] buf = new char[length * 2];

            int bufIndex = 0;
            for (int i = offset; i < offset + length; i++) {
                byte b = array[i];
                buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
                buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
            }
            return new String(buf);
        }
    }

    public static String toHexString(int i) {
        return toHexString(toByteArray(i), false);
    }

    public static byte[] toByteArray(byte b) {
        byte[] array = new byte[1];
        array[0] = b;
        return array;
    }

    public static byte[] toByteArray(int i) {
        byte[] array = new byte[4];

        array[3] = (byte) (i & 0xFF);
        array[2] = (byte) ((i >> 8) & 0xFF);
        array[1] = (byte) ((i >> 16) & 0xFF);
        array[0] = (byte) ((i >> 24) & 0xFF);

        return array;
    }
}

Related

  1. toHex(ByteBuffer data)
  2. toHexStr(final ByteBuffer data)
  3. toHexStream(ByteBuffer data)
  4. toHexString(ByteBuffer bb)
  5. toHexString(ByteBuffer bb)
  6. toHexString(ByteBuffer buffer)
  7. toHexString(ByteBuffer buffer)
  8. toHexString(ByteBuffer buffer, int size)
  9. toHexString(ByteBuffer byteBuffer)