java输出hex(ByteArrayOutputStream)

时间:2012-03-29 12:54:00

标签: java

我有:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
encoder.encode(question, outputStream);

System.out.println(outputStream)打印出来时...我看到0►☻☺♣▬♂test some我希望在HEX中看到这个30 04 12 54 33

我该怎么做?

由于

我能够将二进制文件写入这样的文件:

File file = new File("out.bin");
FileOutputStream filename = new FileOutputStream(file);
outputStream.writeTo(filename);

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

尽管System.out.println()方法可以打印出不同的内容,但它主要用于打印字符串。为此,它将尝试根据平台或某些明确给定的字符编码将输入转换为字符串。要将原始字节打印为十六进制,在打印之前需要进行一些操作。以下示例可能对您有用。

import java.io.*;

class PrintHex
{
    public static void main(String[] args) 
    {
        byte[] raw = {0x30,0x04,0x12,0x54,0x33};
        byte[] raw1 = {'G','I','F'};
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ByteArrayOutputStream bo1 = new ByteArrayOutputStream();
        bo.write(raw,0,raw.length);
        bo1.write(raw1,0,raw1.length);

        System.out.println(bo);
        System.out.println(bo1);

        System.out.println("0x" + getHex(raw));
        System.out.println("0x" + getHex(raw1));
    }
    static final String HEXES = "0123456789ABCDEF";

    public static String getHex( byte [] raw ) {
        if ( raw == null ) {
           return null;
        }
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
        for ( final byte b : raw ) {
           hex.append(HEXES.charAt((b & 0xF0) >> 4))
         .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
   }
}

getHex方法来自http://www.rgagnon.com/javadetails/java-0596.html