public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
答案 0 :(得分:4)
这是一个完整的程序,其中包含asBytes()
函数,这是我假设您正在寻找的,与asHex()
相反:
public class Temp {
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static byte[] asBytes (String s) {
String s2;
byte[] b = new byte[s.length() / 2];
int i;
for (i = 0; i < s.length() / 2; i++) {
s2 = s.substring(i * 2, i * 2 + 2);
b[i] = (byte)(Integer.parseInt(s2, 16) & 0xff);
}
return b;
}
static public void main(String args[]) {
byte[] b = Temp.asBytes("010203040506070809fdfeff");
String s = Temp.asHex(b);
System.out.println (s);
}
}
答案 1 :(得分:1)
要获取字节数组的十六进制字符串表示形式,可以将String.format()
与%X
format specifier一起使用:
public static String asHex(byte buf[])
{
StringBuffer strbuf = new StringBuffer(buf.length * 2);
for (byte b : buf)
strbuf.append(String.format("%02X", b));
return strbuf.toString();
}
以下方法给出了逆操作,返回十六进制字符串的字节数组表示。它使用Byte.parseByte()
并进行一些位移以在一个字节中获得两个字符:
public static byte[] asBytes(String str)
{
if ((str.length() % 2) == 1) str = "0" + str; // pad leading 0 if needed
byte[] buf = new byte[str.length() / 2];
int i = 0;
for (char c : str.toCharArray())
{
byte b = Byte.parseByte(String.valueOf(c), 16);
buf[i/2] |= (b << (((i % 2) == 0) ? 4 : 0));
i++;
}
return buf;
}