Java examples for java.lang:Hex
writes message data to a buffer in hex format
/******************************************************************************* * Copyright (c) 2004, 2007 Boeing.//from w ww. jav a 2 s. co m * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ //package com.java2s; import java.nio.ByteBuffer; public class Main { public static void main(String[] argv) throws Exception { StringBuilder strBuilder = new StringBuilder(); byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; int offset = 2; int length = 2; int columnNum = 2; printByteDump(strBuilder, data, offset, length, columnNum); } /** * writes message data to a buffer in hex format */ public static void printByteDump(StringBuilder strBuilder, byte[] data, int offset, int length, int columnNum) { printByteDump(strBuilder, data, offset, length, columnNum, true); } /** * writes message data to a buffer in hex format */ public static void printByteDump(StringBuilder strBuilder, byte[] data, int offset, int length, int columnNum, boolean hex) { int columnCount = 0; final int endIndex = offset + length; for (int i = offset; i < endIndex; i++) { if (columnCount == columnNum) { strBuilder.append('\n'); columnCount = 0; } if (hex) { strBuilder.append(String.format("%02x ", data[i])); } else { strBuilder.append(data[i]).append(' '); } columnCount++; } strBuilder.append('\n'); } public static void printByteDump(StringBuilder strBuilder, ByteBuffer data, int offset, int length, int columnNum) { int currentPosition = data.position(); // data.position(offset); int columnCount = 0; final int endIndex = offset + length; for (int i = offset; i < endIndex; i++) { if (columnCount == columnNum) { strBuilder.append('\n'); columnCount = 0; } strBuilder.append(String.format("%02x ", data.get(i))); columnCount++; } strBuilder.append('\n'); data.position(currentPosition); } }