When you use GetBytes From String in Java, the return result will depend on the default encoding of your computer (for example: StandardCharsetsUTF-8 or StandardCharsets.ISO_8859_1etc ...).
So, whenever you want getBytes from a String object. Be sure to specify the encoding. eg:
String sample = "abc"; Byte[] a_byte = sample .getBytes(StandardCharsets.UTF_8);
Check what happened to the code. In java, a string called sample is stored in Unicode. each char in String, stored for 2 bytes.
sample : value: "abc" in Memory(Hex): 00 61 00 62 00 63 a -> 00 61 b -> 00 62 c -> 00 63
But, when we get Bytes From String, we have
Byte[] a_byte = sample .getBytes(StandardCharsets.UTF_8) //result is : 61 62 63 //length: 3 bytes Byte[] a_byte = sample .getBytes(StandardCharsets.UTF_16BE) //result is : 00 61 00 62 00 63 //length: 6 bytes
To get a single byte of a string. We can just read the string memory and get every byte of String.Below - this is an example code:
public static byte[] charArray2ByteArray(char[] chars){ int length = chars.length; byte[] result = new byte[length*2+2]; int i = 0; for(int j = 0 ;j<chars.length;j++){ result[i++] = (byte)( (chars[j] & 0xFF00) >> 8 ); result[i++] = (byte)((chars[j] & 0x00FF)) ; } return result; }
Customs:
String sample = "abc"; //First get the chars of the String,each char has two bytes(Java). Char[] sample_chars = sample.toCharArray(); //Get the bytes byte[] result = charArray2ByteArray(sample_chars). //Back to String. //Make sure we use UTF_16BE. Because we read the memory of Unicode of //the String from Left to right. That the same reading //sequece of UTF-16BE. String sample_back= new String(result , StandardCharsets.UTF_16BE);
junqiang chen Jan 15 '16 at 3:33 2016-01-15 03:33
source share