在调试的时候,如果要显示byte的值是否与预期一致,一般转换为16进制的字符串,或者使用base64转换后,然后显示出来。
[java] view
plaincopy
-
-
-
public
static String str2HexStr(String str) { -
-
char[] chars "0123456789ABCDEF".toCharArray();= -
StringBuilder sb = new StringBuilder( ""); -
byte[] bs = str.getBytes(); -
int bit; -
for ( inti 0;= i < bs.length; i++) { -
bit = (bs[i] & 0x0f0) >> 4; -
sb.append(chars[bit]); -
bit = bs[i] & 0x0f; -
sb.append(chars[bit]); -
} -
return sb.toString(); -
}
-
-
-
-
public
static String hexStr2Str(String hexStr) { -
String str = "0123456789ABCDEF"; -
char[] hexs = hexStr.toCharArray(); -
byte[] bytes new= byte[hexStr.length() / 2]; -
int n; -
for ( inti 0;= i < bytes.length; i++) { -
n = str.indexOf(hexs[2 * 16;i]) * -
n += str.indexOf(hexs[2 * 1]);i + -
bytes[i] = (byte) (n 0xff);& -
} -
return new String(bytes); -
}
-
-
-
public
static String byte[]byte2HexStr( b) { -
String hs = ""; -
String stmp = ""; -
for ( intn 0;= n < b.length; n++) { -
stmp = (Integer.toHexString(b[n] & 0XFF)); -
if (stmp.length() 1)== -
hs = hs + "0" + stmp; -
else -
hs = hs + stmp; -
// if (n -
} -
return hs.toUpperCase(); -
}
-
-
private
static byte uniteBytes(String src0, String src1) { -
byte b0 "0x"= Byte.decode( + src0).byteValue(); -
b0 = (byte) (b0 4);<< -
byte b1 "0x"= Byte.decode( + src1).byteValue(); -
byte ret byte)= ( (b0 | b1); -
return ret; -
}
-
-
-
public
static byte[] hexStr2Bytes(String src) { -
int m 0,= n 0;= -
int l 2;= src.length() / -
System.out.println(l); -
byte[] ret new= byte[l]; -
for ( inti 0;= i < l; i++) { -
m = i * 2 + 1; -
n = m + 1; -
ret[i] = uniteBytes(src.substring(i * 2, m), src.substring(m, n)); -
} -
return ret; -
}
-
-
-
public
static String throwsstr2Unicode(String strText) Exception { -
char c; -
String strRet = ""; -
int intAsc; -
String strHex; -
for ( inti 0;= i < strText.length(); i++) { -
c = strText.charAt(i); -
intAsc = (int) c; -
strHex = Integer.toHexString(intAsc); -
if (intAsc 128)> { -
strRet += "//u" + strHex; -
} else { -
// 低位在前面补00 -
strRet += "//u00" + strHex; -
} -
} -
return strRet; -
}
-
-
-
public
static String unicode2Str(String hex) { -
int t 6;= hex.length() / -
StringBuilder str = new StringBuilder(); -
for ( inti 0;= i < t; i++) { -
String s = hex.substring(i * 6, (i 1)+ * 6); -
// 高位需要补上00再转 -
String s1 = s.substring(2, 4) + "00"; -
// 低位直接转 -
String s2 = s.substring(4); -
// 将16进制的string转为int -
int n 16)= Integer.valueOf(s1, + 16);Integer.valueOf(s2, -
// 将int转换为字符 -
char[] chars = Character.toChars(n); -
str.append(new String(chars)); -
} -
return str.toString(); -
}