1

public
class
hello
{
2
public
static
void
main(String a[])
throws
java.io.IOException
{
3
String tmp
=
"
中文
"
;
4
printHex(tmp,
"
Unicode
"
);
5
printHex(tmp,
"
GB2312
"
);
6
printHex(tmp,
"
ISO8859-1
"
);
7
printHex(tmp,
"
UTF-8
"
);
8
}
9
10
private
static
void
printHex(String str,String charset)
throws
java.io.IOException
{
11
byte
[] buf
=
str.getBytes(charset);
12
for
(
int
i
=
0
; i
<
buf.length; i
++
)
{
13
System.out.print(Integer.toHexString(buf[i]));
14
System.out.print(
"
"
);
15
}
16
System.out.println(
"
"
);
17
}
18
19
}

public
class
hello
{2

public
static
void
main(String a[])
throws
java.io.IOException
{3
String tmp
=
"
中文
"
; 4
printHex(tmp,
"
Unicode
"
);5
printHex(tmp,
"
GB2312
"
);6
printHex(tmp,
"
ISO8859-1
"
);7
printHex(tmp,
"
UTF-8
"
);8
}
9

10

private
static
void
printHex(String str,String charset)
throws
java.io.IOException
{11
byte
[] buf
=
str.getBytes(charset);12

for
(
int
i
=
0
; i
<
buf.length; i
++
)
{13
System.out.print(Integer.toHexString(buf[i]));14
System.out.print(
"
"
);15
}
16
System.out.println(
"
"
);17
}
18

19
}
本文通过一个简单的Java程序展示了不同字符编码(如Unicode、GB2312、ISO8859-1和UTF-8)下中文字符串的十六进制表示。通过对同一字符串采用多种编码方式的比较,有助于理解各种编码的特点及适用场景。
1144

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



