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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。