Recently, when communicating with the navigation device, and the device, you need to pass the string in UTF-16 encoding.
How do I convert a string to byte[]? In fact, Java provides a ready-made implementation: Java.lang.string.getbytes ();
Usage: byte[] b=str.getbytes (charsetname)
stringStr="Nanjing";//The default is big-endian when the byte order is not setbyte[] B=str.getbytes ("UTF-16");//result ==0xfe,0xff,0x53,0x57,0x4e,0xac//To the visible character after the discovery of 2 bytes, that is, two bytes of bold, in fact, these two bytes is not the Chinese character "Nanjing" corresponds to, it is the Getbyts method before returning the result of the//used to identify the byte sequence of the output byte array, Feff is the big end, Fffe is small//how to specify the converted byte order, in fact, after the code behind the home is or le can bebyte[] B1_be=str.getbytes ("Utf-16be");//be is big end, result ==0x53,0x57,0x4e,0xacbyte[] B1_le=str.getbytes ("Utf-16le");//le small end, result ==0x4e,0xac,0x53,0x57//As the above example shows, after specifying the byte order, the GetBytes method returns 4 bytes, and the prefix does not have a byte-order identifier.
People who have done the communication know that there is encoding and decoding, then how to convert a byte array into a string by encoding, that is, the reverse operation of GetBytes.
I do this: people who have done the communication know that there is code decoding, then how to convert a byte array into a string by encoding, that is, the reverse operation of GetBytes.
That's what I did:
// after a given byte array, you need to specify the byte order New String (B1_be,"utf-16be"); System. out. println (PRODUCTNO); // = = Nanjing
Summary of the conversion of string and bytes in Java