Mtaraby
Mtaraby

Reputation: 157

Convert array of bytes to string then back it to array of bytes again

I am a beginner in Java, I have array of bytes that I need to convert to string.
After that I want to change it back from string to array of bytes.
I tried the code below, but it did not work since the return value from line 2 does not match the original array:

byte[] comData = byteArray;
String value = new String(comData);
byte[] comData2 = value.getBytes();
// comData2 does not equal comData 

Upvotes: 4

Views: 1615

Answers (3)

user1241335
user1241335

Reputation:

try it so:

byte[] comData = byteArray;
String value = new String();
for(byte me : comData)
{
    value += (char)me;
}
byte[] comData2;
{
    List<byte> temp;
    for(int i=0; i<value.size(); i++)//it may be value.length(), I don't remember
    {
        temp.add(byte(value.getChar(i)));
    }
}
comData2 = temp.getArray();
}

The main problem you're encountering is that you try to use the byte values as the constructor... and then convert the STRING to bytes. You should convert it to char and back using simple casting, in that case it will be the same 0 and 1s.

NOTE some names may vary as I don't keep all of the Java API in my head ;)

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

It's a bit odd that the returned array does not match the original. However, there may be some subtle character encoding issue. Try specifying an explicit encoding for the bytes, e.g.:

byte[] comData = byteArray;
String value = new String(comData, "UTF-8");
byte[] comData2 = value.getBytes("UTF-8");

System.out.println(Arrays.equals(comData, comData2) ? "Success" : "Failure");

Since you say you are a beginner in Java, it's worth noting that you cannot compare the two arrays using == or .equals(). Both of those test whether the arrays are the same object, not whether they have the same contents.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499950

If this is an arbitrary collection of bytes, i.e. it isn't actually encoded text, then I'd recommend you use base64. There's a public domain library available which makes it easy (or various other third party libraries).

Sample code:

byte[] originalData = ...
String base64 = Base64.encode(myByteArray);
byte[] decoded = Base64.decode(base64);

Your original code assumes that the data represents text encoded in the platform default encoding. You should almost always avoid using the platform default encoding - if you do want to use a text encoding, it's usually better to specify one, e.g.

byte[] encodedText = text.getBytes("utf-8");

(Of course, if you're decoding the binary data, then you can't choose the encoding - you need to know which encoding to use.)

Upvotes: 5

Related Questions