Java Hex用法

半兽人 发表于: 2018-04-28   最后更新时间: 2018-04-28  
  •   13 订阅,214 游览

maven引入:

<dependency>
  <groupId>com.madgag.spongycastle</groupId>
  <artifactId>core</artifactId>
  <version>1.53.0.0</version>
</dependency>

上代码:

package org.dreams.transaction.hex;

import org.spongycastle.util.encoders.Hex;

public class HexDemo {
    public static void main(String[] args) {
        String str = "I love you";
        System.out.println("test string : " + str);

        // 方式一,使用Spongy Castle的方式
        byte[] hexec = Hex.encode(str.getBytes());
        System.out.println("Spongy Castle.encode:" + new String(hexec));
        System.out.println("Spongy Castle.decode:" + new String(Hex.decode(hexec)));
        System.out.println();

        // 方式二,解析原理
        String hexEncode = HexUtil.encode(str.getBytes());
        System.out.println("HexUtil.encode Result : " + hexEncode);

        byte[] bytes = HexUtil.decode(hexEncode);
        System.out.println("HexUtil.decode Result : " + new String(bytes));

        System.out.println(Hex.toHexString(str.getBytes()));
        System.out.println(new String(Hex.decode(hexEncode)));
    }

    public static class HexUtil {

        /**
         * 字节流转成十六进制表示
         */
        public static String encode(byte[] src) {
            String strHex = "";
            StringBuilder sb = new StringBuilder("");
            for (int n = 0; n < src.length; n++) {
                strHex = Integer.toHexString(src[n] & 0xFF);
                sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示,位数不够,高位补0
            }
            return sb.toString().trim();
        }

        /**
         * 字符串转成字节流
         */
        public static byte[] decode(String src) {
            int m = 0, n = 0;
            int byteLen = src.length() / 2; // 每两个字符描述一个字节
            byte[] ret = new byte[byteLen];
            for (int i = 0; i < byteLen; i++) {
                m = i * 2 + 1;
                n = m + 1;
                int intVal = Integer.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
                ret[i] = Byte.valueOf((byte) intVal);
            }
            return ret;
        }
    }
}






发表于: 2月前   最后更新时间: 2月前   游览量:214
上一条: Spring SmartLifecycle的用法
下一条: RSA加密算法的java实现

评论…


  • 评论…
    • in this conversation
      提问