JAVA 的字符编码问题

9 min read

基础类型占多大内存

image-20210430121307818

  • String 字符串本质是由一系列的字符(char)组成的

  • utf-8 utf-16是 Unicode编码的具体实现

  • utf-8 英文使用一个字节 汉字使用两个字节

  • utf-16 中英文都是使用两个字节

  • char 基于是Unicode编码规范的,使用utf-16进行编码

一个字符串占用多少字节?

public class Main {

  public static void main(String[] args) {
    String s = new String("A中文");
    byte[] bytes = s.getBytes(StandardCharsets.UTF_16);
    for (byte b : bytes) {
      System.out.println(b);
    }

  }

}

打印结果

-2
-1
0
65
78
45
101
-121

返回的结果-1 , -2 是什么?

BOM

因为操作系统的区别导致 utf-16的两个字符的编码不一样,从而有 uft-16beutf-16le的区别,在使用utf-16时,会在二进制数这前加两个字符"-2 -1" 代表了低位字节在后,高码在前的区别,也就是uft-16be