Java ByteBuffer to Hex asHexString(ByteBuffer buffer)

Here you can find the source of asHexString(ByteBuffer buffer)

Description

Represent as a String all the bytes (in hex format) in a ByteBuffer.

License

Open Source License

Parameter

Parameter Description
buffer ByteBuffer used

Return

String representation of the ByteBuffer

Declaration

public static String asHexString(ByteBuffer buffer) 

Method Source Code

//package com.java2s;
// *|            This source code is provided under the Apache 2.0 license      --

import java.nio.ByteBuffer;

public class Main {
    /**/* www.j a v a 2 s .c o  m*/
     * Represent as a String all the bytes (in hex format) in a ByteBuffer.
     * 
     * @param buffer ByteBuffer used
     * @return String representation of the ByteBuffer
     */
    public static String asHexString(ByteBuffer buffer) {
        final int charsPerLine = 16;
        StringBuilder asString = new StringBuilder();
        StringBuilder currentLine = new StringBuilder();
        StringBuilder all = new StringBuilder();

        boolean processedFirst = false;
        int currentChar = 0;
        int length = buffer.limit();
        int eobyte = 0;

        for (int i = buffer.position(); i < length; i++) {
            if (!(currentChar < charsPerLine)) {
                all.append(currentLine.toString());
                all.append("  ");
                all.append(asString.toString());

                currentLine.setLength(0);
                asString.setLength(0);
                currentChar = 0;
                eobyte = 0;
            }

            byte b = buffer.get(i);
            currentLine.append(eobyte % 2 != 0 ? String.format("%02X ", b)
                    : String.format("%02X", b));
            eobyte ^= 1;

            if (b > 31 && b < 127)
                asString.append((char) b);
            else
                asString.append('.');

            if (currentChar == 7) {
                currentLine.append(" ");
            }
            ++currentChar;
        }

        if (currentLine.length() > 0) {
            if (processedFirst) {
                all.append("\n");
                eobyte = 0;
            }

            int fill = currentChar;
            while (fill < charsPerLine) {
                currentLine.append("   ");

                if (fill == 7) {
                    currentLine.append(" ");
                }
                ++fill;
            }

            all.append(currentLine.toString());
            all.append("  ");
            all.append(asString.toString());
        }

        return all.toString();
    }
}

Related

  1. asHexString(StringBuilder temp, ByteBuffer buffer)
  2. byteBufferToHex(ByteBuffer buffer)
  3. bytesToHex(ByteBuffer bytes)
  4. bytesToHex(ByteBuffer bytes)