views:

1766

answers:

2
+2  Q: 

Hex to Ascii? Java

Hi.

I'm looking for a way to convert hex to ascii in Java. An example:

               byte temps[] = new byte[4];

               temps[0] = 0x74;
               temps[1] = 0x65;
               temps[2] = 0x73;
               temps[3] = 0x74;

               String foo = ..(temps);
               System.out.print(foo);

That should output "test". Anyone an idea?

I appreciate every help!

+4  A: 

You mean like String(byte[] bytes, String encoding) ?

But watch those encodings! You're taking a set of bytes and you need to specify how to encode those as characters. You can use a version of the above that uses a default encoding, but (depending on your application) that could cause you grief further down the line. So I normally specify an encoding (most usually UTF-8).

I note you specify byte-to-ASCII, so I would explicitly specify the ASCII encoding Charset.US-ASCII. Don't rely on the encoding that your JVM runs with!

Brian Agnew
The question says ASCII, so the questioner should probably write ASCII in as the encoding.
tialaramex
Ah. It does indeed. Answer amended
Brian Agnew
+1  A: 
String foo = new String(temps);
Jon