2019.04.08—Java 中字母汉字占几个字节

今天在做回顾的时候看到的问题:
为什么两个运行的结果不一样呢?
1、弄清java中的字节与字符 问题
在java中 , 一个字符等于多少字节?或者更详细的问:在java中 , 一个英文字符等于多少字节?一个中文字符等于多少字节?
答案
Java采用来表示字符 , java中的一个char是2个字节 , 一个中文或英文字符的编码都占2个字节 , 但如果采用其他编码方式 , 一个字符占用的字节数则各不相同 。
在 GB 2312 编码或 GBK 编码中 , 一个英文字母字符存储需要1个字节 , 一个汉子字符存储需要2个字节 。
在UTF-8编码中 , 一个英文字母字符存储需要1个字节 , 一个汉字字符储存需要3到4个字节 。
在UTF-16编码中 , 一个英文字母字符存储需要2个字节 , 一个汉字字符储存需要3到4个字节(扩展区的一些汉字存储需要4个字节) 。
在UTF-32编码中 , 世界上任何字符的存储都需要4个字节 。
举个列子
@Testpublic void test1() throws UnsupportedEncodingException {String a = "名";System.out.println("UTF-8编码长度:"+a.getBytes("UTF-8").length);System.out.println("GBK编码长度:"+a.getBytes("GBK").length);System.out.println("GB2312编码长度:"+a.getBytes("GB2312").length);System.out.println("==========================================");String c = "0x20001";System.out.println("UTF-8编码长度:"+c.getBytes("UTF-8").length);System.out.println("GBK编码长度:"+c.getBytes("GBK").length);System.out.println("GB2312编码长度:"+c.getBytes("GB2312").length);System.out.println("==========================================");char[] arr = Character.toChars(0x20001);String s = new String(arr);System.out.println("char array length:" + arr.length);System.out.println("content:|" + s + " |");System.out.println("String length:" + s.length());System.out.println("UTF-8编码长度:"+s.getBytes("UTF-8").length);System.out.println("GBK编码长度:"+s.getBytes("GBK").length);System.out.println("GB2312编码长度:"+s.getBytes("GB2312").length);System.out.println("==========================================");}

2019.04.08—Java 中字母汉字占几个字节

文章插图
运行结果:
UTF-8编码长度:3
GBK编码长度:2
编码长度:2
==========================================
UTF-8编码长度:4
【2019.04.08—Java 中字母汉字占几个字节】GBK编码长度:1
编码长度:1
==========================================
char array :2
:| ? |
:2
UTF-8编码长度:4
2019.04.08—Java 中字母汉字占几个字节

文章插图
GBK编码长度:1
编码长度:1
==========================================
所以可以添加编码转换:
package com.company;import java.io.UnsupportedEncodingException;public class Main {public static void main(String[] args) throws UnsupportedEncodingException {// write your code hereString str = "J学";String aa = "学";System.out.println("UTF-8编码长度:"+aa.getBytes("UTF-8").length);System.out.println("GBK编码长度:"+aa.getBytes("GBK").length);System.out.println("GB2312编码长度:"+aa.getBytes("GB2312").length);System.out.println("==========================================");String str1 = "学习 Java 编程";int byte_len = str.getBytes().length;int len = str.length();System.out.println("字节长度为:" + byte_len);System.out.println("字符长度为:" + len);byte[] a = str.getBytes();byte[] b = str1.getBytes();byte[] c = aa.getBytes("GBK");try {a = str.getBytes("utf-8");// b = charToByte(x);} catch (Exception e) {e.printStackTrace();}for (int i = 0; i