16進数、文字列の相互変換
1977 ワード
16進数、文字列の相互変換
/** */
/**
* 16 byte[]
*
* @param src
* @return
*/
public static byte[] hexStr2Bytes(String src) {
if (src == null || src.length() == 0)
return null;
int m = 0, n = 0;
int l = src.length() / 2;
byte[] ret = new byte[l];
for (int i = 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;
}
/**
* byte[] 16
*
* @param b
* @return
*/
public static String byteToHexStr(byte[] b) {
if (b == null)
return "";
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
private static byte uniteBytes(String src0, String src1) {
byte b0 = Byte.decode("0x" + src0).byteValue();
b0 = (byte) (b0 << 4);
byte b1 = Byte.decode("0x" + src1).byteValue();
byte ret = (byte) (b0 | b1);
return ret;
}
/**
*
*/
public static String decodeEmpower0(ByteArrayInputStream in) throws IOException {
byte[] bytes = IOUtils.toByteArray(in);
List<String> list = new LinkedList<String>();
for (int i = 0, len = bytes.length; i < len; i++) {
String b = Integer.toHexString(bytes[i] & 0xFF);
if (1 == b.length()) {
list.add("0" + b);
} else {
list.add(b);
}
}
Collections.reverse(list);
return StringUtils.join(list, "");
}