Possible Duplicate:
Conversion of byte[] into a String and then back to a byte[]

I have the following piece of code, I'm trying to get the test to pass, but can't seem to get my head around the various forms of encoding that go on in the java world.

import java.util.Arrays;

class Test {

static final byte[] A = { (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0x00, (byte)0xAA };

public static void main(String[] args) {

    String s = new String(A);

    byte[] b = s.getBytes();

    if (Arrays.equals(A,b)) { 
       System.out.println("TEST PASSED!"); 
    }
    else {
       System.out.println("TEST FAILED!");
    }

}
}

I guess my question is: What is the correct way to convert a byte array of arbitary bytes to a Java String, then later on convert that same Java String to another byte array, which will have the same length and same contents as the original byte array?

link|improve this question

38% accept rate
I get test passed, are you sure you're running your latest code? – Mike K. Sep 22 '11 at 1:18
What's the encoding of your original byte array? – Mark Elliot Sep 22 '11 at 1:19
1  
@Mike K: ideone.com/To8IK – Xander Tulip Sep 22 '11 at 1:20
@MarkElliot: This is some binary data, there is no underlying 'encoding' for A. – Xander Tulip Sep 22 '11 at 1:21
1  
@Xander Tulip If there is a string, there is always encoding. If you print out the bytes individually for(byte iB : b) System.out.println(Integer.toHexString(iB ));, you'll see the trouble starts at 0x88. – Bala R Sep 22 '11 at 1:24
feedback

closed as exact duplicate by Tim Post Oct 3 '11 at 14:12

This question covers exactly the same content as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ for guidance on how to improve it.

2 Answers

up vote 2 down vote accepted

Try a specific encoding:

String s = new String(A, "ISO-8859-1");

byte[] b = s.getBytes("ISO-8859-1");

ideone link

link|improve this answer
that looks like it did the trick. I was one follow up question, is it correct to use a java String to pass a byte array across JNI boundaries? – Xander Tulip Sep 22 '11 at 1:33
1  
@XanderTulip I'm not really familiar with JNI but there generally using string to represent byte array could be lossy. Isn't there a jbyteArray type for this? – Bala R Sep 22 '11 at 1:36
1  
@XanderTulip You can pass byte arrays across JNI boundaries.See java.sun.com/developer/onlineTraining/Programming/JDCBook/… – Ryan Schipper Sep 22 '11 at 2:06
feedback

Use Base64.

Apache Commons Codec has a Base64 class which supports the following interface:

String str = Base64.encodeBase64String(bytes);
byte[] newBytes = Base64.decodeBase64(str);
link|improve this answer
feedback

Not the answer you're looking for? Browse other questions tagged or ask your own question.