Skip to content

Instantly share code, notes, and snippets.

@flour4445
Last active December 20, 2015 03:09
Show Gist options
  • Save flour4445/6061302 to your computer and use it in GitHub Desktop.
Save flour4445/6061302 to your computer and use it in GitHub Desktop.
HexDumpEncoderの代わりになるものを作ろうとしてみた
package net.flourity.lib;
import java.io.*;
public class HexDump
{
public static String hexDump(byte[] b)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream stream = new PrintStream(out);
ByteArrayInputStream in = new ByteArrayInputStream(b);
String str = null;
int line = 0;
byte[] buf = new byte[16];
try
{
while(true)
{
int len = reads(in, buf);
if(len==0) break;
writeHex(out, (byte)((line >>> 8) & 0xff));
writeHex(out, (byte)(line & 0xff));
out.write(58);
out.write(32);
for(int i=0;i<len;i++)
{
writeHex(out, buf[i]);
out.write(32);
if(i==7)
{
out.write(32);
out.write(32);
}
}
if(len<16) break;
out.write(32);
for(int i=0;i<16;i++)
{
int c = buf[i];
out.write((c<32 || c>122) ? 46 : c);
}
stream.println();
line += 16;
}
str = out.toString("8859_1");
}
catch(IOException e)
{
throw new RuntimeException(e);
}
return str;
}
private static int reads(InputStream in, byte[] buf) throws IOException
{
final int len = buf.length;
for(int i=0;i<len;i++)
{
int j = in.read();
if(j==-1) return i;
buf[i] = (byte)j;
}
return len;
}
private static void writeHex(OutputStream out, byte b) throws IOException
{
int c = (b >>> 4) & 15;
c += c>9 ? 55 : 48;
out.write(c);
c = b& 15;
c += c>9 ? 55 : 48;
out.write(c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment