Android byte array to string to byte array

2020-06-27 06:54发布

问题:

All I need is convert byte[] to String. Then do something with that string and convert back to byte[] array. But in this testing I'm just convert byte[] to string and convert back to byte[] and the result is different.

to convert byte[] to string by using this:

byte[] byteEntity = EntityUtils.toByteArray(entity);
String s = new String(byteEntity,"UTF-8");

Then i tried:

byte[] byteTest = s.getBytes("UTF-8");

Then i complared it:

if (byteEntity.equals(byteTest) Log.i("test","equal");
else Log.i("test","diff");

So the result is different.

I searched in stackoverflow about this but it doesn't match my case. The point is my data is .png picture so the string converted is unreadable. Thanks in advance.

回答1:

Solved

Using something like this.

byte[] mByteEntity = EntityUtils.toByteArray(entity);
byte[] mByteDecrypted = clip_xor(mByteEntity,"your_key".getBytes());
baos.write(mByteDecrypted);
InputStream in = new ByteArrayInputStream(baos.toByteArray());

and this is function clip_xor

protected byte[] clip_xor(byte[] data, byte[] key) {
    int num_key = key.length;
    int num_data = data.length;

    try {
        if (num_key > 0) {
            for (int i = 0, j = 0; i < num_data; i++, j = (j + 1)
                    % num_key) {
                data[i] ^= key[j];
            }
        }
    } catch (Exception ex) {
        Log.i("error", ex.toString());
    }
    return data;
}

Hope this will useful for someone face same problem. Thanks you your all for helping me solve this.

Special thanks for P'krit_s



回答2:

primitive arrays are actually Objects (that's why they have .equals method) but they do not implement the contract of equality (hashCode and equals) needed for comparison. You cannot also use == since according to docs, .getBytes will return a new instance byte[]. You should use Arrays.equals(byteEntity, byteTest) to test equality.



回答3:

Have a look to the answer here.

In that case my target was transform a png image in a bytestream to display it in embedded browser (it was a particular case where browser did not show directly the png).

You may use the logic of that solution to convert png to byte and then to String.

Then reverse the order of operations to get back to the original file.