During the development of Android client and server interfaces, the author encountered this problem, because the stream inputstream and outputstream operations are used, and the parameters are in the byte type, when designing the Protocol, it is inevitable to convert it to the string type, and then identify it on the server side and perform the next operation, however, when byte type is converted to the string type, garbled characters may occur. At first, I was puzzled. Later, according to the description of the tostring () method in Java Doc, find the relevant solution-use the string constructor and pass in the byte array as the parameter.
The details are as follows: string type character/String Conversion to byte type: String S = "Hello, world "; // define the string variable byte [] B = new byte [1024]; // initialize the Byte object B = S. getbytes (); // convert the string variable byte. The result is B = s in B. getbytes (charset); // The value of charset can be
Charset |
Description |
| US-ASCII |
Seven-bit ASCII, a.k..ISO646-US, A.k. A. The basic Latin block of the Unicode Character Set |
| ISO-8859-1 |
ISO Latin Alphabet No. 1, a.k..ISO-LATIN-1 |
| UTF-8 |
Eight-bit UCS Transformation Format |
| UTF-16BE |
Sixteen-bit UCS Transformation format, big-Endian byte order |
| UTF-16LE |
Sixteen-bit UCS Transformation format, little-Endian byte order |
| UTF-16 |
Sixteen-bit UCS Transformation format, byte order identified by an optional byte-order mark |
B = S. getbytes (string charsetname); B = getbytes (INT srcbegin, int srcend, byte [] DST, int dstbegin); a string of the string type can be converted to the byte type through the above methods, so how can we convert byte arrays to the string type? If: String S1 = B. tostring (); the result printed on the console is [B @ de6ced, which is obviously not the result we need. What should we do in this case? Let's take a look at the definition of the tostring () function in Java Doc:
Tostring
Public String tostring ()
Returns the string representation of the object. Generally, the tostring method returns a string that "represents the object in text. The results should be concise but easy to understand.
We recommend that you override this method for all subclasses.
The tostring method of the object class returns a string consisting of the Class Name (the object is an instance of the class) the at tag "@" and the unsigned hexadecimal representation of the object's hash code. In other words, this method returns a string whose value is equal:
Getclass (). getname () + '@' + integer. tohexstring (hashcode ())
Return Value:
String Representation of the object.
According to the above meaning, B. tostring () returns a hexadecimal unsigned number and a hash code, which is different from the data we need. Therefore, the tostring () method cannot be used. The correct method is to use byte array as a parameter and use string to construct a string, that is, string S1 = new string (B.