Skip to content

Instantly share code, notes, and snippets.

@t-yamo t-yamo/Base62.java
Created May 13, 2015

Embed
What would you like to do?
62進数Javaコードサンプル(Base62)
package sample.util;
import java.math.BigInteger;
/**
* Base62ユーティリティ。
* [0-9A-Za-z]の順番で0から対応する。ASCIIコードの並び順に合わせて大文字の方が先なので注意。
* 'Z'は35、'i'は44、'z'は61。
* @author t-yamo
*/
public final class Base62 {
private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int BASE = CHARS.length();
private static final BigInteger BIG_BASE = BigInteger.valueOf(BASE);
private Base62() {
// N/A
}
/**
* longからBase62への変換。
* @param num 変換元数値。
* @return Base62。
*/
public static String encode(long num) {
if (num <= 0) {
return "0";
}
StringBuilder sb = new StringBuilder();
while (num > 0) {
int sup = (int) (num % BASE);
sb.append(CHARS.charAt(sup));
num = num / BASE;
}
return sb.reverse().toString();
}
/**
* Base62からlongへの変換。
* @param str 変換元Base62。
* @return long。
*/
public static long decode(String str) {
BigInteger num = BigInteger.valueOf(0);
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
int index = CHARS.indexOf(chars[chars.length - i - 1]);
num = num.add(BIG_BASE.pow(i).multiply(BigInteger.valueOf(index)));
}
return num.longValue();
}
}
package sample.util;
import org.junit.Assert;
import org.junit.Test;
/**
* @author t-yamo
*/
public class Base62Test {
@Test
public void testEncode() {
Assert.assertEquals("0", Base62.encode(0));
Assert.assertEquals("6", Base62.encode(6));
Assert.assertEquals("Z", Base62.encode(35));
Assert.assertEquals("i", Base62.encode(44));
Assert.assertEquals("z", Base62.encode(61));
Assert.assertEquals("1YsaPe", Base62.encode(1431537942)); // 2015-05-13 17:25:42 UTCの秒
Assert.assertEquals("PCaRJdA", Base62.encode(1431537942000l)); // 2015-05-13 17:25:42 UTCのミリ秒
Assert.assertEquals("2FEQDJkH9F", Base62.encode(30400066288418849l));
Assert.assertEquals("1Zyk6HmZO9", Base62.encode(21392905688514741l));
Assert.assertEquals("1dqNWdRcwg", Base62.encode(22236810928128038l));
Assert.assertEquals("6Rhvv3b0J", Base62.encode(1407619700686911l));
}
@Test
public void testDecode() {
Assert.assertEquals(0, Base62.decode("0"));
Assert.assertEquals(6, Base62.decode("6"));
Assert.assertEquals(35, Base62.decode("Z"));
Assert.assertEquals(44, Base62.decode("i"));
Assert.assertEquals(61, Base62.decode("z"));
Assert.assertEquals(1431537942, Base62.decode("1YsaPe")); // 2015-05-13 17:25:42 UTCの秒
Assert.assertEquals(1431537942000l, Base62.decode("PCaRJdA")); // 2015-05-13 17:25:42 UTCのミリ秒
Assert.assertEquals(30400066288418849l, Base62.decode("2FEQDJkH9F"));
Assert.assertEquals(21392905688514741l, Base62.decode("1Zyk6HmZO9"));
Assert.assertEquals(22236810928128038l, Base62.decode("1dqNWdRcwg"));
Assert.assertEquals(1407619700686911l, Base62.decode("6Rhvv3b0J"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.