1 public class Code {
2
3 public static void main(String[] args) throws Exception{
4 // TODO Auto-generated method stub
5 String s="自己练习";
6 byte[] byte1=s.getBytes();//将字符串转化为字符数组,用项目默认的编码
7 for (byte b : byte1) {
8 //把字节以十六进制的方式显示
9 System.out.print(Integer.toHexString(b&0xff)+" ");
10 }
11 System.out.println( );
12 //jbk中文占用两个字节,英文占用一个字节
13 byte[] byte2=s.getBytes("gbk");
14 for (byte b : byte2) {
15 System.out.print(Integer.toHexString(b&0xff)+" ");
16 }
17 //其中个utf-8中文占用三个字节,英文占用一个字节
18 System.out.println();
19 byte[] byte3=s.getBytes("utf-8");
20 for (byte b : byte3) {
21 System.out.print(Integer.toHexString(b&0xff)+" ");
22 }
23 //java是双字节编码,utf-16be编码
24 //其中中文占用两个字节,英文占用两个字节
25 System.out.println();
26 byte[] byte4=s.getBytes("utf-16be");
27 for (byte b : byte4) {
28 System.out.print(Integer.toHexString(b&0xff)+" ");
29 }
30 System.out.println();
31 String st1=new String(byte4,"utf-16be");
32 System.out.print(st1);
33
34 System.out.println();
35 byte[] byte5=s.getBytes("US-ASCII");
36 for (byte b : byte5) {
37 System.out.print(Integer.toHexString(b&0xff)+" ");
38 }
39 }
40
41 }
![]()