Skip to content

Instantly share code, notes, and snippets.

@werand
Created September 21, 2018 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save werand/e273eba76f4771609b88aabe45bd9323 to your computer and use it in GitHub Desktop.
Save werand/e273eba76f4771609b88aabe45bd9323 to your computer and use it in GitHub Desktop.
HexDump Java-Class
import java.util.AbstractList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class HexDump
{
private static final int _16 = 16;
private static class ByteList extends AbstractList<Integer>
{
private byte[] bytes;
private int startIndex;
private int length;
public ByteList(byte[] bytes, int startIndex, int length)
{
this.bytes = bytes;
this.startIndex = startIndex;
this.length = length;
if (bytes.length < startIndex + length)
{
this.length = bytes.length - startIndex;
}
}
@Override
public Integer get(int index)
{
return Integer.valueOf(bytes[index + startIndex] & 0xff);
}
@Override
public int size()
{
return length;
}
}
public static String getAsHexString(byte[] bytes)
{
return IntStream.range(0, (bytes.length / _16) + 1)
.mapToObj(i -> new ByteList(bytes, i * _16, _16))
.map(HexDump::toHexRow)
.collect(Collectors.joining());
}
private static String toHexRow(List<Integer> row)
{
String filler = "";
if (row.size() < _16)
{
filler = getBlanks((_16 - row.size()) * 3);
}
return row.stream().map(HexDump::toHex).collect(Collectors.joining()) + filler + row.stream().map(HexDump::printableChar).collect(Collectors.joining()) + "\n";
}
private static String getBlanks(int count)
{
return new String(new char[count]).replace("\0", " ");
}
private static String toHex(Integer i)
{
return String.format("%02x ", Integer.valueOf(i.intValue()&0xff));
}
private static String printableChar(Integer i)
{
return i.intValue() >= 32 && i.intValue() < 127 ? String.valueOf((char) i.intValue()) : ".";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment