java Base36 算法

2019/01/03 16:05
阅读数 66
package com.github.linushp.wsblog.utils;


import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Base36 {

    private static final Charset CHAT_SET_UTF8 = StandardCharsets.UTF_8;

    public static String encode(byte[] inputBytes) {
        if (inputBytes == null || inputBytes.length == 0) {
            return "";
        }
        BigInteger bigInteger = new BigInteger(inputBytes);
        String xx = bigInteger.toString(36);
        if (xx.charAt(0) == '-') {
            StringBuffer stringBuffer = new StringBuffer(xx);
            stringBuffer.setCharAt(0, 'f');
            return stringBuffer.toString();
        } else {
            return "z" + xx;
        }
    }

    public static String encode(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        return encode(str.getBytes(CHAT_SET_UTF8));
    }

    public static byte[] decode(String str) {
        if (str == null || str.isEmpty()) {
            return new byte[]{};
        }

        String str1;
        if (str.charAt(0) == 'z') {
            str1 = str.substring(1);
        } else {
            str1 = "-" + str.substring(1);
        }
        BigInteger bigInteger = new BigInteger(str1, 36);
        return bigInteger.toByteArray();
    }

    public static String decodeStr(String str) {
        if (str == null || str.isEmpty()){
            return "";
        }
        byte[] bytes1 = decode(str);
        return new String(bytes1, CHAT_SET_UTF8);
    }

}

  

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部