java n占用字节_JAVA中英文占用字节数

JAVA对中文默认使用的是UTF-8编码

JAVA对于不同编码,所占的字节数是不同的。

具体如下:

英文字母:A

默认情况下字节数:1

字节数:1;编码:GB2312

字节数:1;编码:GBK

字节数:1;编码:GB18030

字节数:1;编码:ISO-8859-1

字节数:1;编码:UTF-8

字节数:4;编码:UTF-16

字节数:2;编码:UTF-16BE

字节数:2;编码:UTF-16LE

中文汉字:人

默认情况下字节数:3

字节数:2;编码:GB2312

字节数:2;编码:GBK

字节数:2;编码:GB18030

字节数:1;编码:ISO-8859-1

字节数:3;编码:UTF-8

字节数:4;编码:UTF-16

字节数:2;编码:UTF-16BE

字节数:2;编码:UTF-16LE

中英混合:hello世界

默认情况下字节数:11

字节数:9;编码:GB2312

字节数:2;编码:GBK

字节数:9;编码:GB18030

字节数:7;编码:ISO-8859-1

字节数:11;编码:UTF-8

字节数:16;编码:UTF-16

字节数:14;编码:UTF-16BE

字节数:14;编码:UTF-16LE

测试代码如下:

/**

* java中文字符所占字节数测试

*/

import java.io.UnsupportedEncodingException;

public class EncodeTest {

public static void printByteLength(String s, String encodingName) {

System.out.print("字节数:");

try {

System.out.print(s.getBytes(encodingName).length);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

System.out.println(";编码:" + encodingName);

}

public static void main(String[] args) {

String en = "A";

String ch = "人";

String en_ch = "hello世界";

// 计算一个英文字母在各种编码下的字节数

System.out.println("英文字母:" + en);

System.out.printf("默认情况下字节数:" + en.getBytes().length + "\n");

EncodeTest.printByteLength(en, "GB2312");

EncodeTest.printByteLength(en, "GBK");

EncodeTest.printByteLength(en, "GB18030");

EncodeTest.printByteLength(en, "ISO-8859-1");

EncodeTest.printByteLength(en, "UTF-8");

EncodeTest.printByteLength(en, "UTF-16");

EncodeTest.printByteLength(en, "UTF-16BE");

EncodeTest.printByteLength(en, "UTF-16LE");

System.out.println();

// 计算一个中文汉字在各种编码下的字节数

System.out.println("中文汉字:" + ch);

System.out.printf("默认情况下字节数:" + ch.getBytes().length + "\n");

EncodeTest.printByteLength(ch, "GB2312");

EncodeTest.printByteLength(ch, "GBK");

EncodeTest.printByteLength(ch, "GB18030");

EncodeTest.printByteLength(ch, "ISO-8859-1");

EncodeTest.printByteLength(ch, "UTF-8");

EncodeTest.printByteLength(ch, "UTF-16");

EncodeTest.printByteLength(ch, "UTF-16BE");

EncodeTest.printByteLength(ch, "UTF-16LE");

// 计算一个中英混合在各种编码下的字节数

System.out.println("中英混合:" + en_ch);

System.out.printf("默认情况下字节数:" + en_ch.getBytes().length + "\n");

EncodeTest.printByteLength(en_ch, "GB2312");

EncodeTest.printByteLength(ch, "GBK");

EncodeTest.printByteLength(en_ch, "GB18030");

EncodeTest.printByteLength(en_ch, "ISO-8859-1");

EncodeTest.printByteLength(en_ch, "UTF-8");

EncodeTest.printByteLength(en_ch, "UTF-16");

EncodeTest.printByteLength(en_ch, "UTF-16BE");

EncodeTest.printByteLength(en_ch, "UTF-16LE");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值