16进制字符串与字节数组之间的转换
一个16进制字符占4位,一个字节8位,意味着一个字节存储两个16进制数。所以我们要将16进制转成字节就需要两个16进制数。
·
思路
一个16进制数占4位,一个字节8位,意味着一个字节存储两个16进制数。所以我们要将16进制转成一个字节就需要两个16进制数。
- 从左往右,两两一组将字符分开。
- 两个字符一组当成一个字节,分别判断两个字符在a-z、A-Z、0-9哪个区间,然后用字符减去a或者A或者0的字符,得到差,如果是A-Z或者a-z,那么需要加10。
- 将第一个字符当成16进制的高位,并左移4个位。
- 将3步骤左移4个位之后的字节|(或)第二个字符的字节数,得到这一组的16进制最终的字节。

如果是将字节转成十六进制串,则是上面的逆操作。
java代码
public class HexCode {
private static final char[] UPPER_HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static final char[] LOWER_HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static char[] encode2char(byte[] bytes, boolean lowercase) {
char[] chars = new char[bytes.length*2];
for (int i = 0; i < chars.length; i = i + 2) {
byte b = bytes[i / 2];
char[] HEX_CHARS = LOWER_HEX_CHARS;
if (!lowercase) {
HEX_CHARS = UPPER_HEX_CHARS;
}
chars[i] = HEX_CHARS[(b >> 0x4) & 0xf];
chars[i + 1] = HEX_CHARS[b & 0xf];
}
return chars;
}
public static String encode(byte[] bytes, boolean lowercase) {
char[] endata = encode2char(bytes, lowercase);
return new String(endata);
}
public static byte[] decode(String data) throws Exception {
int len = (data.length()+1)/2;
byte[] bytes = new byte[len];
int index = 0;
for (int i = 1; i< data.length(); i+=2) {
char h = data.charAt(i-1);
char l = data.charAt(i);
bytes[index] = decodeByte(h,l);
index++;
}
return bytes;
}
public static byte decodeByte(char hight, char low) throws Exception {
byte data = 0;
if (hight>='A' && hight <= 'F') {
int value = hight-'A'+10;
data = (byte)(value<<4);
} else if (hight>='a' && hight <= 'f') {
int value = hight-'a'+10;
data = (byte)(value<<4);
} else if (hight>='0' && hight <= '9') {
int value = hight-'0';
data = (byte)(value<<4);
} else {
throw new Exception("decode hexadecimal failed");
}
if (low>='A' && low <= 'F') {
int value = low-'A'+10;
data |= (byte)value;
} else if (low>='a' && low <= 'f') {
int value = low-'a'+10;
data |= (byte)value;
} else if (low>='0' && low <= '9') {
int value = low-'0';
data |= (byte)value;
} else {
throw new Exception("decode hexadecimal failed");
}
return data;
}
public static void main(String[] args) throws Exception {
String hexStr = "C2B109";
byte[] bs = decode(hexStr);
for (byte b : bs) {
System.out.printf("%08d%n",Integer.valueOf(Integer.toBinaryString(Byte.toUnsignedInt(b))));
}
System.out.println(encode(bs,false));
}
}
更多推荐


所有评论(0)