美文网首页
2020-08-03 android tools hex 字符串

2020-08-03 android tools hex 字符串

作者: fjasmin | 来源:发表于2020-08-03 19:15 被阅读0次
  1. android 常用工具类。字符串转数组。数组转字符串。

HexUtil.java

/**
 * 字符串转字节工具类
 */
public class HexUtil {
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHexString(byte[] b) {
        if (b.length == 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < b.length; i++) {
            int value = b[i] & 0xFF;
            String hv = Integer.toHexString(value);
            if (hv.length() < 2) {
                sb.append(0);
            }

            sb.append(hv);
        }
        return sb.toString();
    }
}

相关文章

网友评论

      本文标题:2020-08-03 android tools hex 字符串

      本文链接:https://www.haomeiwen.com/subject/lbjvrktx.html