The number of bytes in Java that are literal characters

Source: Internet
Author: User

In the Java language, the number of bytes in Chinese characters depends on how the character is encoded, and in general, when iso8859-1 encoding is used, a Chinese character is only 1 bytes as an English character, and a Chinese character is 2 bytes when using GB2312 or GBK encoding. , while using UTF-8 encoding, a Chinese character will account for 3 bytes. We can get the byte array by the String class GetBytes (String CharsetName) method, which is encoded with the specified encoding, and the length of the byte array is the number of bytes that the string takes up in the specified encoding mode.

"Test Sample"

 Public classTest { Public Static voidMain (String []args)throwsunsupportedencodingexception {//Run Result: 2SYSTEM.OUT.PRINTLN ("Test". GetBytes ("Iso8859-1")). length); //Run Result: 4SYSTEM.OUT.PRINTLN ("Test". GetBytes ("GB2312")). length); //Run Result: 4SYSTEM.OUT.PRINTLN ("Test". GetBytes ("GBK")). length); //Run Result: 6SYSTEM.OUT.PRINTLN ("Test". GetBytes ("UTF-8")). length); }}

Note the GetBytes () method with no parameters for the String class is converted in the default encoding of the platform that the program runs on, with different results under different platforms, so the GetBytes (String CharsetName) method with the specified encoding is recommended.

The number of bytes in Java that are literal characters

Related Article

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.