java - java中英文和汉字各占多少字节?
问题描述
import java.io.UnsupportedEncodingException;
public class TestChar {
public static void main(String[] args) throws UnsupportedEncodingException {
String cnStr = "龙";
String enStr = "a";
byte[] cnBytes = cnStr.getBytes("UTF-8");
byte[] enBytes = enStr.getBytes("UTF-8");
System.out.println("bytes size of Chinese:" + cnBytes.length);
System.out.println("bytes size of English:" + enBytes.length);
// in java, char takes two bytes, the question is:
char cnc = '龙'; // will '龙‘ take two or three bytes ?
char enc = 'a'; // will 'a' take one or two bytes ?
}
}
输出:
bytes size of Chinese:3
bytes size of English:1
这里,My JVM 设置为 UTF-8,从输出中我们知道汉字“龙”占 3 个字节,英文字符“a”占 1 个字节。我的问题是:
在 Java 中,char 占用两个字节,这里,char cnc = '龙'; 字符编码 = 'a'; cnc 只需要两个字节而不是 3 个字节吗?'a' 需要两个字节而不是一个字节?
解决方案
UTF-8是一种变长字符编码,其中字符占用 1 到 4 个字节。
Javachar
是 16 位的。请参阅Java 语言规范中的3.1 Unicode以了解 Java 究竟如何处理 Unicode。
推荐阅读
- graphql - 如何在 GraphQL 中将两个模型连接到一个模型
- python - 分组但不使用 Python/Pandas 的 groupby 函数
- python - Flask API 中的多个函数
- typescript - 使用 Typescript 类语法在 Oak 中获取当前上下文
- reactjs - ReactJS - ChartJS 中的图表在第一页加载后重新渲染
- arrays - 如何遍历数组并通过关键字存储到新数组中
- azure - 无法通过 Bash 删除文件
- ios - 无法理解 Xcode 的变量视图
- android - 发送带有文件的电子邮件时出错
- macos - 为什么我在 Finder 中找不到 Chromium,如何删除它?