Summary of the conversion of string and bytes in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.