Java ByteBuffer to Hex toHex(ByteBuffer data)

Here you can find the source of toHex(ByteBuffer data)

Description

Convert data from given ByteBuffer to hex

License

Open Source License

Parameter

Parameter Description
data a parameter

Return

hex

Declaration

public static String toHex(ByteBuffer data) 

Method Source Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**/*w  w  w.j  av  a  2  s . com*/
     * Convert data from given ByteBuffer to hex
     *
     * @param data
     * @return hex
     */
    public static String toHex(ByteBuffer data) {
        StringBuilder result = new StringBuilder();
        int counter = 0;
        int b;
        while (data.hasRemaining()) {
            if (counter % 16 == 0)
                result.append(String.format("%04X: ", counter));

            b = data.get() & 0xff;
            result.append(String.format("%02X ", b));

            counter++;
            if (counter % 16 == 0) {
                result.append("  ");
                toText(data, result, 16);
                result.append("\n");
            }
        }
        int rest = counter % 16;
        if (rest > 0) {
            for (int i = 0; i < 17 - rest; i++) {
                result.append("   ");
            }
            toText(data, result, rest);
        }
        return result.toString();
    }

    /**
     * Gets last <tt>cnt</tt> read bytes from the <tt>data</tt> buffer and puts into <tt>result</tt> buffer in special
     * format:
     * <ul>
     * <li>if byte represents char from partition 0x1F to 0x80 (which are normal ascii chars) then it's put into buffer as
     * it is</li>
     * <li>otherwise dot is put into buffer</li>
     * </ul>
     *
     * @param data
     * @param result
     * @param cnt
     */
    private static void toText(ByteBuffer data, StringBuilder result, int cnt) {
        int charPos = data.position() - cnt;
        for (int a = 0; a < cnt; a++) {
            int c = data.get(charPos++);
            if (c > 0x1f && c < 0x80)
                result.append((char) c);
            else
                result.append('.');
        }
    }
}

Related

  1. bytesToHexString(ByteBuffer b)
  2. toHex(ByteBuffer bb)
  3. toHex(ByteBuffer bb)
  4. toHex(ByteBuffer buf)
  5. toHex(ByteBuffer buffer)
  6. toHexStr(final ByteBuffer data)
  7. toHexStream(ByteBuffer data)
  8. toHexString(ByteBuffer bb)
  9. toHexString(ByteBuffer bb)