Created
January 18, 2024 13:54
-
-
Save xialeistudio/abd42f676be6a7141c4d65427f5cec83 to your computer and use it in GitHub Desktop.
base62
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Base62 { | |
private final static String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
private final static int BASE = CHARS.length(); | |
public static String encode(long number) { | |
var sb = new StringBuilder(); | |
while (number > 0) { | |
var ch = CHARS.charAt((int) (number % BASE)); | |
number /= BASE; | |
sb.insert(0, ch); | |
} | |
return sb.toString(); | |
} | |
public static long decode(String str) { | |
long number = 0; | |
int power = 0; | |
for (int i = str.length() - 1; i >= 0; i--) { | |
var ch = str.charAt(i); | |
var digit = CHARS.indexOf(ch); | |
number += (long) (digit * Math.pow(BASE, power)); | |
power++; | |
} | |
return number; | |
} | |
public static void main(String[] args) { | |
var num = 170916032679263329L; | |
System.out.println(encode(num)); | |
System.out.println(decode(encode(num))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment