package practice.encode;
import java.io.UnsupportedEncodingException;
public class EncodeDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String s="心情ABC";
byte[] byte1=s.getBytes();//转换为字节码数组用的是项目默认编码GBK
for (byte b : byte1) {
//GBK编码中文占用两个字节,英文占用一个字节
System.out.print(Integer.toHexString(b &0xff)+" ");
}
System.out.println();
byte[] byte2=s.getBytes("utf-8");
for (byte b : byte2) {
//utf-8编码中文占用三个字节,英文占用一个字节
System.out.print(Integer.toHexString(b &0xff)+" ");
}
System.out.println();
//Java是双字节编码 utf-16be
byte[] byte3=s.getBytes("utf-16be");
for (byte b : byte3) {
//utf-16be编码中文占用两个字节,英文占用两个字节
System.out.print(Integer.toHexString(b &0xff)+" ");
}
System.out.println();
String str1=new String(byte3);//字节码数组用的utf-16be编码,转换为字符串时用的默认编码GBK,出现乱码
System.out.println(str1);
String str2=new String(byte3,"utf-16be");//转换为字符串时也用utf-16be编码
System.out.println(str2);
}
}
编码学习
最新推荐文章于 2024-12-23 09:15:33 发布
本文通过一个Java实例演示了不同字符集编码方式下字符串的字节表示差异,包括默认的GBK编码、UTF-8编码以及UTF-16be编码,并展示了如何正确地将字节码数组转换回原始字符串。
1381

被折叠的 条评论
为什么被折叠?



