Base62Util.java 2.26 KB
package com.sitech.util;

import java.math.BigInteger;
import java.util.UUID;

/**
 *
 * @author liujhc <liujhc@si-tech.com.cn>
 */
public class Base62Util {

    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final BigInteger divisor = BigInteger.valueOf(ALPHABET.length());

    public static String encode(BigInteger integer) {
        BigInteger bi = integer.shiftLeft(1);
        if (bi.signum() == -1) {//如果是负数,变为正数加1
            bi = bi.negate().add(BigInteger.ONE);
        }
        StringBuilder sb = new StringBuilder();
        while (bi.signum() != 0) {
            BigInteger[] arr = bi.divideAndRemainder(divisor);
            bi = arr[0];
            sb.append(ALPHABET.charAt(arr[1].intValue()));
        }
        return sb.reverse().toString();
    }

    public static BigInteger decodeToInteger(String str) {
        BigInteger bi = BigInteger.ZERO;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            String v = String.valueOf(ALPHABET.indexOf(str.charAt(len - 1 - i)));
            bi = new BigInteger(v).multiply(divisor.pow(i)).add(bi);
        }
        if (bi.getLowestSetBit() == 0) {
            bi = bi.subtract(BigInteger.ONE).negate();
        }
        return bi.shiftRight(1);
    }

    public static String encode(byte[] bytes) {
        return encode(new BigInteger(bytes));
    }

    public static String encode(long num) {
        return encode(BigInteger.valueOf(num));
    }

    public static byte[] decodeToBytes(String str) {
        return decodeToInteger(str).toByteArray();
    }

    /**
     * 通过此方法生成的随机UUID只有22位长
     *
     * @return
     */
    public static String encodeUUID(UUID uuid) {
        long msb = uuid.getMostSignificantBits(), lsb = uuid.getLeastSignificantBits();
        return encode(BigInteger.valueOf(msb).shiftLeft(64).add(BigInteger.valueOf(lsb)));
    }

    /**
     * 通过此方法生成的随机UUID只有22位长
     *
     * @return
     */
    public static UUID decodeToUUID(String base62tr) {
        BigInteger bi = decodeToInteger(base62tr);
        long lsb = bi.longValue();
        long msb = bi.shiftRight(64).longValue();
        return new UUID(msb, lsb);
    }
}