How can I create my desired string using a byte array?
I have the following byte array:
byte[] bytes = new byte[] { (byte) -61, (byte) -61};
At first I convert it to String using the following line:
strResult = new String(bytes, "ISO_8859_1");
Then I convert it back to byte array using the following code:
byte[] myBytes = strResult.getBytes();
The content of myBytes is [-61, -125, -61, -125]
I have tested "US-ASCII" and "UTF-8" charsets. Each one returns a defer开发者_如何学JAVAent string that none of them is [-61, -61].
How can I create a String containing [-61, -61] bytes?
I mean I want to have a string when I use getBytes(); it returns [-61, -61] bytes. How can I create it?
You should use the same encoding to convert back again:
byte[] myBytes = strResult.getBytes("ISO_8859_1");
Basically the string doesn't maintain any record of the encoding originally used to create it - it's always just a sequence of UTF-16 code units. If you don't specify the encoding to use when converting a string to a byte array, it uses the platform default encoding.
Note that if you're trying to encode arbitrary binary data as text (i.e. you're not decoding something which is genuinely text in a particular encoding) then you shouldn't use these methods at all - you should use Base64
to encode and decode safely.
精彩评论