When trying to construct a String from a array of type byte[] and then converting back to byte[] array using String.getBytes(), some byte values are modified. Below is a piece of code that reproduces my issue:
public static void main(String[] args)
{
byte[] arr = new byte[] { (byte)0xff, 0x5e};
String str = new String(arr);
byte[] arr2 = str.getBytes();
for(int i = 0; i < 2; i++)
System.out.print(String.format("%02X ", arr2[i]));
for(int i = 0; i < 2; i++)
System.out.print(String.format("%02X ", arr[i]));
}
The output is as follows:
3F 5E FF 5E
I have tried conversion with all of standard charsets and yet the result is the same. For a reason I'm not able to figure out, 0xFF becomes 0x3F... Why, and how do I correct this?
getBytes()andnew String(). A 1-byte encoding such asISO-8859-1should work just fine.new String(arr, "ISO-8859-1");the conversion works okay.