Table of Contents
The relationship between Unicode and UTF-8/UTF-16/UTF-32
UTF-16
Codepoint related in java
Home Java javaTutorial Detailed introduction to some things related to codepoint and UTF-16 in Java

Detailed introduction to some things related to codepoint and UTF-16 in Java

Mar 21, 2017 am 11:11 AM

The relationship between Unicode and UTF-8/UTF-16/UTF-32

The relationship between Unicode and UTF-8/UTF-16/UTF-32 is Character set and encoding Relationship. The concept of character set actually includes two aspects, one is the set of characters and the other is the encoding scheme. A character set defines all the symbols it contains. A character set in a narrow sense does not include an encoding scheme. It just defines all the symbols that belong to this character set. But generally speaking, a character set doesn't just define a collection of characters, it also defines a binary encoding for each symbol. When we mention GB2312 or ASCII, it implicitly indicates that the encoding scheme is GB2312 or ASCII. In these cases, the character set and encoding scheme can be considered equal.

But Unicode has multiple encoding schemes. The standard encoding scheme specified by the Unicode character set is UCS-2 (UTF-16), which uses two bytes to represent a Unicode character (two bytes in UTF-16 are basic multilingual flat characters, 4 bytes are auxiliary plane characters). UCS-4 (UTF-32) uses 4 bytes to represent a Unicode character. Another commonly used Unicode encoding scheme - UTF-8 uses 1 to 4 variable-length bytes to represent a Unicode character, and can be obtained directly from UTF-16 from a simple conversion algorithm. Therefore, there are multiple encoding schemes when using the Unicode character set, which are used in appropriate scenarios.

To put it more simply, the Unicode character set is equivalent to a dictionary, which records all characters (i.e. images) and their corresponding Unicode codes (regardless of the specific encoding scheme), UTF-8/ UTF-16/UTF-32 code is the data calculated by Unicode code through corresponding formulas and actually stored and transmitted.

UTF-16

The JVM specification clearly states that the encoding scheme used by java's char type is UTF-16, so let's first understand UTF-16.

Unicode's encoding space ranges from U+0000 to U+10FFFF. There are 1112064 code points (code points) that can be used to map characters. The code point is the digital form of the character. This part of the coding space can be divided into 17 planes, each plane containing 2^16 (65536) code bits. The first plane is called the Basic Multilingual Plane (BMP), or Plane 0. Other planes are called Supplementary Planes. In the basic multilingual plane, the code point blocks from U+D800 to U+DFFF are permanently reserved and are not mapped to Unicode characters. UTF-16 uses the reserved code bits of the 0xD800-0xDFFF section to encode the code bits of the auxiliary plane characters.

The most commonly used characters are included in BMP and are represented by 2 bytes. The code bits in the auxiliary plane are encoded into a pair of 16-bit long code elements in UTF-16, called a surrogate pair. The specific method is:

  • Subtract 0×10000 from the code bit, and the resulting value ranges from 0 to 0xFFFFF, which is 20 bits long.

  • The high 10-bit value (the value range is 0~0x3FF) is added to 0xD800 to obtain the first code element or called the high surrogate, the value range It is 0xD800~0xDBFF. Since the value of the high-order proxy is smaller than that of the low-order proxy, in order to avoid confusion, the Unicode standard now calls the high-order proxy lead surrogates.

  • The low 10-bit value (the value range is also 0~0x3FF) is added with 0xDC00 to get the second symbol or called the low surrogate. The current value is The range is 0xDC00~0xDFFF. Since the low-order surrogate has a larger value than the high-order surrogate, in order to avoid confusion, the Unicode standard now calls the low-order surrogate trail surrogates.

For example, U+10437 encoding:

  • 0×10437 minus 0×10000, the result is 0×00437, which in binary is 0000 0000 0100 0011 0111.

  • Partition its upper 10-bit value and lower 10-bit value (using binary): 0000000001 and 0000110111.

  • Add 0xD800 to the upper value to form the high bit: 0xD800 + 0×0001 = 0xD801.

  • Add 0xDC00 to the lower value to form the low bit: 0xDC00 + 0×0037 = 0xDC37.

Since the code points of the leading agent, trailing agent, and valid characters in BMP do not overlap with each other, it is impossible for a part of one character encoding to be the same as another character encoding during search. Different parts overlap. So you can determine the starting code element of the next character for a given character by examining only one code element (the basic unit that makes up a code point, 2 bytes).

For a string object, its content is stored through a char array. The char type is stored in 2 bytes, and these 2 bytes actually store the code elements under UTF-16 encoding. When we use the charAt and length methods, what is actually returned is a code element and the number of code elements. Although there is generally no problem, if the character is an auxiliary plane character, the above two methods will not get the correct result. The correct processing method is as follows:

int character = aString.codePointAt(i);
int length = aString.codePointCount(0, aString.length());
Copy after login

It should be noted that the return value of codePointAt is int instead of char. This value is the Unicode code.

The codePointAt method calls codePointAtImpl:

static int codePointAtImpl(char[] a, int index, int limit) {
        char c1 = a[index];
        if (isHighSurrogate(c1) && ++index < limit) {
            char c2 = a[index];
            if (isLowSurrogate(c2)) {
                return toCodePoint(c1, c2);
            }
        }
        return c1;
    }
Copy after login

isHighSurrogate method determines whether the 2 bytes of the subscript character are leading surrogates in UTF-16 (0xD800~0xDBFF):

public static boolean isHighSurrogate(char ch) {
        // Help VM constant-fold; MAX_HIGH_SURROGATE + 1 == MIN_LOW_SURROGATE
        return ch >= MIN_HIGH_SURROGATE && ch < (MAX_HIGH_SURROGATE + 1);
    }
Copy after login
public static final char MIN_HIGH_SURROGATE = &#39;\uD800&#39;;
public static final char MAX_HIGH_SURROGATE = &#39;\uDBFF&#39;;
Copy after login

然后++index,isLowSurrogate方法判断下一个字符的2个字节是否为后尾代理(0xDC00~0xDFFF):

public static boolean isLowSurrogate(char ch) {
        return ch >= MIN_LOW_SURROGATE && ch < (MAX_LOW_SURROGATE + 1);
    }
Copy after login
public static final char MIN_LOW_SURROGATE  = &#39;\uDC00&#39;;
public static final char MAX_LOW_SURROGATE  = &#39;\uDFFF&#39;;
Copy after login

toCodePoint方法将这2个码元组装成一个Unicode码:

public static int toCodePoint(char high, char low) {
        // Optimized form of:
        // return ((high - MIN_HIGH_SURROGATE) << 10)
        //         + (low - MIN_LOW_SURROGATE)
        //         + MIN_SUPPLEMENTARY_CODE_POINT;
        return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
                                       - (MIN_HIGH_SURROGATE << 10)
                                       - MIN_LOW_SURROGATE);
    }
Copy after login

这个过程就是以上将一个辅助平面的Unicode码位转换成2个码元的逆过程。

所以,枚举字符串的正确方法:

for (int i = 0; i < aString.length();) {
	int character = aString.codePointAt(i);
	//如果是辅助平面字符,则i+2
	if (Character.isSupplementaryCodePoint(character)) i += 2;
	else ++i;
}
Copy after login

将codePoint转换为char[]可调用Character.toChars方法,然后可进一步转换为字符串:

new String(Character.toChars(codePoint));
Copy after login

toChars方法所做的就是以上将Unicode码位转换为2个码元的过程。

The above is the detailed content of Detailed introduction to some things related to codepoint and UTF-16 in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles