Here you can find the source of hexDump(ByteBuffer buffer)
Write a hexidecimal dump, with byte offsets and character conversions in the style of hexdump -C
, to the standard output stream.
Parameter | Description |
---|---|
buffer | Buffer to dump to the output stream. |
Parameter | Description |
---|---|
NullPointerException | Cannot dump a <code>null</code> buffer. |
public final static void hexDump(ByteBuffer buffer) throws NullPointerException
//package com.java2s; /*// w ww .ja v a2s.c o m * Copyright 2016 Richard Cartwright * * 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; public class Main { /** <p>Hexidecimal character array used for encoding binary data.</p> */ private final static char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * <p>Write a hexidecimal dump, with byte offsets and character conversions in the style of * <code>hexdump -C</code>, to the standard output stream. The buffer is dumped from its current * position to its limit. The buffer is rewound to the initial position.</p> * * @param buffer Buffer to dump to the output stream. * * @throws NullPointerException Cannot dump a <code>null</code> buffer. */ public final static void hexDump(ByteBuffer buffer) throws NullPointerException { if (buffer == null) throw new NullPointerException("Cannot create a hex dump of a null buffer."); int positionCache = buffer.position(); buffer.rewind(); int count = 0; while (buffer.hasRemaining()) { StringBuffer nextLine = new StringBuffer(80); byte[] lineBytes = new byte[buffer.remaining() > 16 ? 16 : buffer.remaining()]; buffer.get(lineBytes); nextLine.append(Integer.toHexString(count)); for (int x = nextLine.length(); x <= 8; x++) nextLine.insert(0, '0'); nextLine.append(" "); for (int x = 0; x < lineBytes.length; x++) { nextLine.append(hexChars[(lineBytes[x] >>> 4) & 15]); nextLine.append(hexChars[lineBytes[x] & 15]); nextLine.append(' '); } nextLine.append(" "); for (int x = 0; x < lineBytes.length; x++) { if ((lineBytes[x] > 0x20) && (lineBytes[x] < 0x80)) nextLine.append((char) lineBytes[x]); else nextLine.append('.'); } System.out.println(nextLine.toString()); count += 16; } buffer.position(positionCache); } }