现在已经写出了一个程序:import java.io.UnsupportedEncodingException;class byteToHex
{
static public String byteToHexString(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
public static void main(String[] args)
{
String P="你好";
byte[] bytes = null;
try {
bytes = P.getBytes("UNICODE");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<bytes.length;i++){
System.out.println(byteToHexString(bytes[i]));
}
}
}我现在程序运行后的结果是
“fe
ff
4f
60
59
7d”我不明白的是“你好”的话不是应该只出现“4f 60 59 7d”么。。最开始的那个“fe ff”这两个是怎么出来的。。
{
static public String byteToHexString(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
public static void main(String[] args)
{
String P="你好";
byte[] bytes = null;
try {
bytes = P.getBytes("UNICODE");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<bytes.length;i++){
System.out.println(byteToHexString(bytes[i]));
}
}
}我现在程序运行后的结果是
“fe
ff
4f
60
59
7d”我不明白的是“你好”的话不是应该只出现“4f 60 59 7d”么。。最开始的那个“fe ff”这两个是怎么出来的。。
刚才试了下,如果是GBK的话就不会在开始的时候出现任何无关字符。。可是我一旦试UNICODE的话就会出现那个fe ff还麻烦大家帮忙看看了。。TVT谢谢!!
http://topic.csdn.net/u/20081009/09/e899898c-591f-4985-ae88-5972475708fb.html关于字节序,可以参考这些文档:UTF-8, UTF-16, UTF-32 & BOM FAQ:
http://unicode.org/faq/utf_bom.htmlRFC 2718 3.2节:
http://www.ietf.org/rfc/rfc2781.txt
另:你要转 Unicode 不需要这样 getByte() 解码,直接使用字符的 int 值就可以了。
System.out.println(toUnicodeByte("你好"));
} public static String toUnicodeByte(String str) {
if(str == null || str.length() == 0) {
return str;
}
char[] chs = str.toCharArray();
char[] bytes = new char[chs.length * 5 + 1];
for(int i = 0, k = 0; i < chs.length; i++) {
if(k > 0) {
bytes[k++] = ' ';
}
bytes[k++] = HEX[(chs[i] >>> 12) & 0xf];
bytes[k++] = HEX[(chs[i] >>> 8) & 0xf];
bytes[k++] = ' ';
bytes[k++] = HEX[(chs[i] >>> 4) & 0xf];
bytes[k++] = HEX[chs[i] & 0xf];
}
return new String(bytes);
}
}
char[] bytes = new char[chs.length * 5 + 1];改为:char[] bytes = new char[chs.length * 6 - 1];StringBuffer buf = new StringBuffer();
char[] cArray = s.toCharArray();
for (char c : cArray) {
buf.append("\\u");
buf.append(Integer.toHexString(c));
}
return buf.toString();
}