你可以用 Integer.toHexString 来转换每一个 byte,但是这样转换不是很整齐,而且,可能会出现 FFFFFFF3 这样的情况,所以需要特别处理。你也可以使用 Character.forDigit 来转换一个 byte,一个 byte 需要转换2次。如下例(两种方法都用了):/*
* @(#) Test.java
* Create By James Fancy
*/
package jamesfancy;public class Test { public static String toHexString1(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; ++i) {
buffer.append(toHexString1(b[i]));
}
return buffer.toString();
} public static String toHexString1(byte b) {
String s = Integer.toHexString(b & 0xFF);
if (s.length() == 1) {
return "0" + s;
} else {
return s;
}
} public static String toHexString2(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; ++i) {
buffer.append(toHexString2(b[i]));
}
return buffer.toString();
} public static String toHexString2(byte b) {
char[] buffer = new char[2];
buffer[0] = Character.forDigit((b >>> 4) & 0x0F, 16);
buffer[1] = Character.forDigit(b & 0x0F, 16);
return new String(buffer);
} public static void main(String[] args) {
byte[] bs = "你好,Java".getBytes();
System.out.println(toHexString1(bs).toUpperCase());
System.out.println(toHexString2(bs).toUpperCase());
}
}
* @(#) Test.java
* Create By James Fancy
*/
package jamesfancy;public class Test { public static String toHexString1(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; ++i) {
buffer.append(toHexString1(b[i]));
}
return buffer.toString();
} public static String toHexString1(byte b) {
String s = Integer.toHexString(b & 0xFF);
if (s.length() == 1) {
return "0" + s;
} else {
return s;
}
} public static String toHexString2(byte[] b) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; ++i) {
buffer.append(toHexString2(b[i]));
}
return buffer.toString();
} public static String toHexString2(byte b) {
char[] buffer = new char[2];
buffer[0] = Character.forDigit((b >>> 4) & 0x0F, 16);
buffer[1] = Character.forDigit(b & 0x0F, 16);
return new String(buffer);
} public static void main(String[] args) {
byte[] bs = "你好,Java".getBytes();
System.out.println(toHexString1(bs).toUpperCase());
System.out.println(toHexString2(bs).toUpperCase());
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货