All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.spring.boxes.dollar.support.cryptor.Base62 Maven / Gradle / Ivy

package com.spring.boxes.dollar.support.cryptor;

import org.apache.commons.lang3.StringUtils;

public class Base62 extends cn.hutool.core.codec.Base62 {

    public static String toBase62(long value) {
        if (value == Long.MIN_VALUE) {
            return LONG_MIN_VALUE_BASE62;
        }
        if (value == 0L) {
            return "0";
        }
        boolean negative = value < 0;
        value = Math.abs(value);
        StringBuilder builder = new StringBuilder();
        while (value > 0) {
            builder.append(ALPHABET.charAt((int) (value % BASE)));
            value = value / BASE;
        }
        return negative ? builder.append(NEGATIVE_CHAR).reverse().toString() : builder.reverse()
                .toString();
    }

    public static long toLongVal(String base62) {
        if (StringUtils.equals(base62, LONG_MIN_VALUE_BASE62)) {
            return Long.MIN_VALUE;
        }

        boolean negative = false;
        if (base62.startsWith(NEGATIVE_CHAR)) {
            negative = true;
            base62 = base62.substring(1);
        }
        long value = 0;
        for (int i = 0; i < base62.length(); i++) {
            value = value * BASE + ALPHABET.indexOf(base62.charAt(i));
        }
        return negative ? -value : value;
    }

    public static boolean isNumberBase62(String base62) {
        if (base62.startsWith(NEGATIVE_CHAR)) {
            base62 = base62.substring(1);
        }
        return StringUtils.containsOnly(base62, ALPHABET);
    }

    private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LONG_MIN_VALUE_BASE62 = "-aZl8N0y58M8";
    private static final String NEGATIVE_CHAR = "-";
    private static final Integer BASE = ALPHABET.length();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy