在Java中字符串由字符char组成, 一个char由两个byte组成, 而一个byte由八个bit组成, 一个十六进制字符(0-F)实际上由4个字节byte即可表达, 因此, 从字节数组到十六进制字符串, 实际上占用的存储空间扩大了4倍。
下面来看一下从十六进制字符串转换为字节数组的方式:
第一种方法: 实际借用了Character类的方法进行16进制的转换
1 static byte[] hexToByteArray2(String hex)
2 {
3 int l = hex.length();
4 byte[] data = new byte[l / 2];
5 for (int i = 0; i < l; i += 2)
6 {
7 data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
8 + Character.digit(hex.charAt(i + 1), 16));
9 }
10 return data;
11 }
第二种方法: 借用了Integer类中的十六进制转换:
1 static byte[] hexToByteArray(String hexString) {
2 byte[] result = new byte[hexString.length() / 2];
3 for (int len = hexString.length(), index = 0; index <= len - 1; index += 2) {
4 String subString = hexString.substring(index, index + 2);
5 int intValue = Integer.parseInt(subString, 16);
6 result[index / 2] = (byte)intValue;
7 }
8 return result;
9 }
从字节数组转换为十六进制的方法:
一、
1 static String byteArrayToHex(byte[] bytes) {
2 StringBuilder result = new StringBuilder();
3 for (int index = 0, len = bytes.length; index <= len - 1; index += 1) {
4 int char1 = ((bytes[index] >> 4) & 0xF);
5 char chara1 = Character.forDigit(char1, 16);
6 int char2 = ((bytes[index]) & 0xF);
7 char chara2 = Character.forDigit(char2, 16);
8 result.append(chara1);
9 result.append(chara2);
10 }
11 return result.toString();
12 }
二、
1 static String byteArrayToHex2(byte[] bytes) {
2 StringBuilder result = new StringBuilder();
3 for (int index = 0, len = bytes.length; index <= len - 1; index += 1) {
4
5 String invalue1 = Integer.toHexString((bytes[index] >> 4) & 0xF);
6 String intValue2 = Integer.toHexString(bytes[index] & 0xF);
7 result.append(invalue1);
8 result.append(intValue2);
9 }
10 return result.toString();
11 }
然后介绍一种更实用的字符串和十六进制之间的转换:
十六进制转字符串:
1 static String hexToString(String hex, Charset charset) {
2 return new String(new BigInteger(hex, 16).toByteArray(), charset);
3 }
字符串转十六进制:
1 static String stringToHex(String arg, Charset charset) {
2 if (arg == null || arg.length() == 0) {
3 return "";
4 }
5 byte[] bytes = arg.getBytes(charset);
6 return String.format("%0" + bytes.length * 2 + "x", new BigInteger(1, bytes));
7 }