
org.seppiko.commons.utils.codec.Base36 Maven / Gradle / Ivy
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.seppiko.commons.utils.codec;
import java.math.BigInteger;
/**
* Base36
* A simple base36 encode / decode.
* Commonly used by URL redirection systems like TinyURL as
* compact alphanumeric identifiers.
*
* @see Base36
* @author Leonard Woo
*/
public class Base36 {
private static final int BASE_COUNT = 36;
private Base36() {}
/**
* Encode bytes to Base36 string
*
* @param data bytes.
* @return Base36 String.
*/
public static String encodeBytes(final byte[] data) {
return encodeBytes(data, false);
}
/**
* Encode bytes to Base36 string
*
* @param data bytes.
* @param toLowercase true is return {@code [0-9a-z]}, false is {@code [0-9A-Z]}.
* @return Base36 String.
*/
public static String encodeBytes(final byte[] data, boolean toLowercase) {
return encode(new BigInteger(1, data), toLowercase);
}
/**
* Encode number to Base36 string
*
* @param source Number.
* @return Base36 String.
*/
public static String encode(final BigInteger source) {
return encode(source, false);
}
/**
* Encode number to Base36 string
*
* @param source Number.
* @param toLowercase true is return {@code [0-9a-z]}, false is {@code [0-9A-Z]}.
* @return Base36 String.
*/
public static String encode(final BigInteger source, boolean toLowercase) {
String base36 = source.toString(BASE_COUNT);
return toLowercase? base36: base36.toUpperCase();
}
/**
* Decode Base36 string to bytes
*
* @param str Base36 String.
* @return bytes.
*/
public static byte[] decodeBytes(final String str) {
return decode(str).toByteArray();
}
/**
* Decode Base36 string to number
*
* @param str Base36 String.
* @return Number.
*/
public static BigInteger decode(final String str) {
return new BigInteger(str, BASE_COUNT);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy