Java Hex用法

半兽人 发表于: 2018-04-28   最后更新时间: 2018-08-29 20:28:23  
{{totalSubscript}} 订阅, 5,647 游览

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;
        }
    }
}

结果:

test string : I love you
Spongy Castle.encode:49206c6f766520796f75
Spongy Castle.decode:I love you

HexUtil.encode Result : 49206c6f766520796f75
HexUtil.decode Result : I love you
49206c6f766520796f75
I love you
更新于 2018-08-29
在线,10小时前登录

查看java更多相关的文章或提一个关于java的问题,也可以与我们一起分享文章