java Base36 算法

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

}

  

posted on 2019-01-03 16:05  袜子破了  阅读(1034)  评论(0编辑  收藏  举报