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);
}
}
编码学习
最新推荐文章于 2021-10-09 15:17:15 发布