forked from LupusNobilis/java-org.hwo
54 lines
1.2 KiB
Java
54 lines
1.2 KiB
Java
package org.hwo;
|
|
|
|
public class ByteArrayHexlifier {
|
|
|
|
protected static char[] hexDigits = "0123456789ABCDEF".toCharArray();
|
|
|
|
public static String byteArrayToString(byte[] bytes)
|
|
{
|
|
char[] target = new char[bytes.length * 2];
|
|
|
|
for (int i=0;i<bytes.length;i++)
|
|
{
|
|
target[2*i+1] = hexDigits[bytes[i] & 0x0f];
|
|
target[(2*i)] = hexDigits[(bytes[i]>>4) & 0x0f];
|
|
}
|
|
|
|
return new String(target);
|
|
}
|
|
|
|
public static byte[] stringToByteArray(String hexstring)
|
|
{
|
|
byte[] buffer;
|
|
int len = hexstring.length();
|
|
|
|
if ((len % 2)!=0)
|
|
len--;
|
|
|
|
buffer = new byte[ len / 2];
|
|
|
|
char[] source = hexstring.toCharArray();
|
|
|
|
for (int i=0;i< buffer.length;i++)
|
|
{
|
|
if ((source[2*i] >= 'A')&&(source[2*i] <= 'F'))
|
|
{
|
|
buffer[i] = (byte)(source[2*i] - 'A' + 10);
|
|
} else if ((source[2*i] >= '0')&&(source[2*i] <= '9'))
|
|
{
|
|
buffer[i] = (byte)(source[2*i] - '0');
|
|
}
|
|
|
|
if ((source[(2*i)+1] >= 'A')&&(source[(2*i)+1] <= 'F'))
|
|
{
|
|
buffer[i] |= (byte)((source[(2*i)+1] - 'A' + 10)<<4);
|
|
} else if ((source[(2*i)+1] >= '0')&&(source[(2*i)+1] <= '9'))
|
|
{
|
|
buffer[i] |= (byte)((source[(2*i)+1] - '0')<<4);
|
|
}
|
|
}
|
|
return buffer;
|
|
}
|
|
|
|
}
|