网站首页 文章专栏 16进制字符串字节数组互转
16进制字符串字节数组互转
编辑时间:2018-11-15 14:47:10 作者:田泽 浏览量:548

字符串转16进制字符串

/**
* 字符串转16进制字符串
* @param str
* @return
*/
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);

}
return sb.toString().trim();
}

public static void main(String[] args) throws UnsupportedEncodingException {
String str = "123456";
System.out.println(str2HexStr(str));
}

结果:

16进制字符串转换成字节数组

            /**
* 16进制字符串转换成字节数组
* @param hexString
* @return byte[]
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}

/**
* @param c
* @return
*/
private static int toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}

public static void main(String[] args) throws UnsupportedEncodingException {
String str = "123456";
System.out.println(str2HexStr(str));
String hexStr = str2HexStr(str);
byte[] item = hexStringToByte(hexStr);
System.out.println(Arrays.toString(item));
}

结果:

解析16进制byte数组

public static void main(String[] args) throws UnsupportedEncodingException {
String str = "123456";
System.out.println(str2HexStr(str));
String hexStr = str2HexStr(str);
byte[] item = hexStringToByte(hexStr);
System.out.println(Arrays.toString(item));
//解析16进制byte数组
System.out.println(new String(item,"UTF-8"));
}

结果:

如果简单使用不包含中文也可以用以下代码

public static void main(String[] args) throws UnsupportedEncodingException {
String str = "123456";
byte[] item = str.getBytes("GBK");
System.out.println(Arrays.toString(item));
System.out.println(new String(item,"UTF-8"));
}

结果:

包含中文还是推荐上面的写法

public static void main(String[] args) throws UnsupportedEncodingException {
String str = "阿萨德";
System.out.println(str2HexStr(str));
String hexStr = str2HexStr(str);
byte[] item = hexStringToByte(hexStr);
System.out.println(Arrays.toString(item));
//解析16进制byte
System.out.println(new String(item,"UTF-8"));
}

结果:


支付宝打赏 微信打赏

您的支持是我最大的动力。

吐槽区