编码学习

来源:互联网 发布:ppt软件哪个好 编辑:程序博客网 时间:2024/06/08 16:40
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();//转换为字节码数组用的是项目默认编码GBKfor (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-16bebyte[] 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);}}

0 0