2

I have :

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

and when System.out.println(outputStream) prints this .. i see 0►☻☺♣▬♂test some and I want to see this in HEX like 30 04 12 54 33

How can I do that ?

Thanks

I was able to write the binary to a file like this :

File file = new File("out.bin");
FileOutputStream filename = new FileOutputStream(file);
outputStream.writeTo(filename);
pufos
  • 2,890
  • 8
  • 34
  • 38
  • look here : http://stackoverflow.com/a/2149927/986169 – giorashc Mar 29 '12 at 12:55
  • for my case is there a solution ? just for this example .. i'm not so good at this so ... :| – pufos Mar 29 '12 at 13:19
  • I write the binary to a file like `outputStream.writeTo(filename)` where file is `File file = new File("out.bin"); FileOutputStream filename = new FileOutputStream(file);` – pufos Mar 29 '12 at 14:55

2 Answers2

1

Can use use Integer.toHexString()? http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toHexString(int)

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • and in my actual case ? i'm trying to figure out because i never did this ... thank you – pufos Mar 29 '12 at 13:04
0

Although the System.out.println() method can print different things out, it is mainly for printing strings. For this purpose, it will try to convert the input into character string according to the platform or some explicitly given character encoding. To print raw bytes as hex, you need some manipulation before printing them out. The following example might be useful to you.

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();
   }
}

The getHex method is from http://www.rgagnon.com/javadetails/java-0596.html

dragon66
  • 2,645
  • 2
  • 21
  • 43
  • pufos, what do you mean by binary to hex? ByteArrayOutputStream to hex? Change ByteArrayOutputStream to byte array first, than use the above method. – dragon66 Mar 29 '12 at 14:03