• 字符串、bute[]数组和十六进制字符串的相互转换


    1、字符串转换成十六进制字符串
    public static String str2HexStr(String str) {
            if (EncodingUtil.isEmpty(str)) {
                return "";
            }
            char[] chars = "0123456789ABCDEF".toCharArray();
            StringBuilder sb = new StringBuilder("");
            byte[] bs = new byte[0];
            try {
                bs = str.getBytes("GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            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();
        }

    2、16进制字符串转换为byte数组

    public static byte[] hexStringToBytes2(String hexString) {
            if (hexString == null) {            // 判断源字符串是否为空
                return null;
            }
            String tmp = "0123456789ABCDEF";
            char[] hexChars = hexString.toCharArray();
            int len = hexString.length();
            byte[] bytes = new byte[len / 2];    // 创建字节数组空间
    
            for (int i = 0; i < len; i += 2) {    //
                bytes[i / 2] = (byte) ((tmp.indexOf(hexChars[i]) << 4) | tmp.indexOf(hexChars[i + 1]));
            }
            return bytes;
        }

     3、byte[]数组转换为16进制字符串

        public static String bytesToHexString(byte[] bytes) {
            if (bytes == null)
                return null;
            StringBuffer stringBuffer = new StringBuffer(bytes.length * 2);
            for (byte b : bytes) {
                if ((b & 0xFF) < 0x10) {
                    stringBuffer.append('0');
                }
                stringBuffer.append(Integer.toHexString(0xFF & b));
            }
    
            return stringBuffer.toString().toUpperCase(Locale.getDefault());
        }
    

      

  • 相关阅读:
    入门5查询生成器
    入门4关键概念
    入门3请求处理
    入门2应用结构
    入门1-基础入门
    PHP代码规范
    Bug总结
    数据结构与常用集合总结
    CSS之使用display:inline-block来布局
    nginx,lvs,haproxy+keepalived区别
  • 原文地址:https://www.cnblogs.com/jing5464/p/10172606.html
Copyright © 2020-2023  润新知