zoukankan      html  css  js  c++  java
  • Hex编码 十六进制编码

    HEX字符串与字节码(字符串)转换工具

    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    
    public class HexUtils {
        public static void main(String[] args) throws Exception {
            test("a");//编码前【a】编码后【61】解码后【a】
            test("A");//编码前【A】编码后【41】解码后【A】
            test("1");//编码前【1】编码后【31】解码后【1】
            test("白");//编码前【白】编码后【E799BD】解码后【白】
            test("白乾涛");//编码前【白乾涛】编码后【E799BDE4B9BEE6B69B】解码后【白乾涛】
            System.out.println(URLEncoder.encode("白乾涛", "UTF-8"));//和上述编码结果一致【%E7%99%BD%E4%B9%BE%E6%B6%9B】
            System.out.println(encodeHex("白乾涛".getBytes("UTF-8")));//使用apache的工具类编码和上述编码结果一致【e799bde4b9bee6b69b】
            System.out.println(new String(decodeHex("e799bde4b9bee6b69b".toCharArray()), "UTF-8"));
        }
        private static void test(String input) throws UnsupportedEncodingException {
            String charsetName = "UTF-8";
            System.out.print("编码前【" + input + "】");
            System.out.print("编码后【" + str2HexStr(input, charsetName) + "】");
            System.out.println("解码后【" + hexStr2Str(str2HexStr2(input, charsetName), charsetName) + "】");
        }
        //******************************************************************************************
        //                                                                      参数或返回值为字符串
        //******************************************************************************************
        /**
         * 将原始字符串转换成16进制字符串【方法一】
         */
        public static String str2HexStr(String input, String charsetName) throws UnsupportedEncodingException {
            byte buf[] = input.getBytes(charsetName);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                //以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式。
                //如果参数为负,那么无符号整数值为参数加上 2^32;否则等于该参数。将该值转换为十六进制(基数 16)的无前导 0 的 ASCII 数字字符串。
                //如果无符号数的大小值为零,则用一个零字符 '0' (’\u0030’) 表示它;否则,无符号数大小的表示形式中的第一个字符将不是零字符。
                //用以下字符作为十六进制数字【0123456789abcdef】。这些字符的范围是从【'\u0030' 到 '\u0039'】和从【'\u0061' 到 '\u0066'】。
                String hex = Integer.toHexString(buf[i] & 0xFF);//其实核心也就这一样代码
                if (hex.length() == 1) hex = '0' + hex;
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        }
        /**
         * 将原始字符串转换成16进制字符串【方法二】
         */
        public static String str2HexStr2(String str, String charsetName) throws UnsupportedEncodingException {
            byte[] bs = str.getBytes(charsetName);
            char[] chars = "0123456789ABCDEF".toCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0, bit; i < bs.length; i++) {
                bit = (bs[i] & 0x0f0) >> 4;
                sb.append(chars[bit]);
                bit = bs[i] & 0x0f;
                sb.append(chars[bit]);
            }
            return sb.toString();
        }
        /**
         * 将16进制字符串转换为原始字符串
         */
        public static String hexStr2Str(String hexStr, String charsetName) throws UnsupportedEncodingException {
            if (hexStr.length() < 1) return null;
            byte[] hexbytes = new byte[hexStr.length() / 2];
            for (int i = 0; i < hexStr.length() / 2; i++) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                hexbytes[i] = (byte) (high * 16 + low);
            }
            return new String(hexbytes, charsetName);
        }
        //******************************************************************************************
        //                                                                      参数或返回值为字节数组
        //******************************************************************************************
        /**
         * 将二进制转换成16进制
         */
        public static String encode(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) hex = '0' + hex;
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        }
        /**
         * 将16进制转换为二进制(服务端)
         */
        public static byte[] deocde(String hexStr) {
            if (hexStr.length() < 1) return null;
            byte[] result = new byte[hexStr.length() / 2];
            for (int i = 0; i < hexStr.length() / 2; i++) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        }
        //******************************************************************************************
        //                          org.apache.commons.codec.binary.Hex的实现方式
        //******************************************************************************************
        private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        public static char[] encodeHex(byte[] data) {
            int l = data.length;
            char[] out = new char[l << 1];
            int i = 0;
            for (int j = 0; i < l; i++) {
                out[(j++)] = DIGITS[((0xF0 & data[i]) >>> 4)];
                out[(j++)] = DIGITS[(0xF & data[i])];
            }
            return out;
        }
        public static byte[] decodeHex(char[] data) throws Exception {
            int len = data.length;
            if ((len & 0x1) != 0) throw new Exception("Odd number of characters.");
            byte[] out = new byte[len >> 1];
            int i = 0;
            for (int j = 0; j < len; i++) {
                int f = toDigit(data[j], j) << 4;
                j++;
                f |= toDigit(data[j], j);
                j++;
                out[i] = ((byte) (f & 0xFF));
            }
            return out;
        }
        private static int toDigit(char ch, int index) throws Exception {
            int digit = Character.digit(ch, 16);
            if (digit == -1) throw new Exception("Illegal hexadecimal charcter " + ch + " at index " + index);
            return digit;
        }
    }
    
  • 相关阅读:
    poj 3321 Apple Tree
    hdu 1520 Anniversary party
    Light OJ 1089 Points in Segments (II)
    Timus 1018 Binary Apple Tree
    zoj 3299 Fall the Brick
    HFUT 1287 法默尔的农场
    Codeforces 159C String Manipulation 1.0
    GraphQL + React Apollo + React Hook 大型项目实战(32 个视频)
    使用 TypeScript & mocha & chai 写测试代码实战(17 个视频)
    GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)
  • 原文地址:https://www.cnblogs.com/baiqiantao/p/6227034.html
Copyright © 2011-2022 走看看