Last active
September 20, 2023 10:05
-
-
Save sblendorio/3455a32d4fcde42e4c4c26977ab9f1c6 to your computer and use it in GitHub Desktop.
Convert long in base N-arbitrary.java
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 String convert(long num, String code) { | |
final int base = code.length(); | |
String text = ""; | |
do { | |
text = code.charAt((int) (num%base)) + text; | |
num /= base; | |
} while (num > 0); | |
return text; | |
} | |
public long toLong(String text, String code) { | |
final long base = code.length(); | |
long num = 0; | |
long pow = 1; | |
int len = text.length(); | |
for (int i = 0; i < len; i++) { | |
num += code.indexOf(text.charAt(len - i - 1)) * pow; | |
pow *= base; | |
} | |
return num; | |
} | |
println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")); | |
println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@=-+*/^%$#&()!?.,:;[]")); | |
println(toLong("Ns8T$87=uh","0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@=-+*/^%$#&()!?.,:;[]")); | |
println(new Date(9223372036854775807L)); | |
public static String convert(BigInteger num, String code) { | |
final BigInteger base = new BigInteger(""+code.length()); | |
String text = ""; | |
do { | |
text = code.charAt( (num.mod(base) ).intValue()) + text; | |
num = num.divide(base); | |
} while (num.signum() > 0); | |
return text; | |
} | |
public static BigInteger toLong(String text, String code) { | |
final BigInteger base = new BigInteger("" + code.length()); | |
BigInteger num = BigInteger.ZERO; | |
BigInteger pow = BigInteger.ONE; | |
int len = text.length(); | |
for (int i = 0; i < len; i++) { | |
BigInteger pos = new BigInteger(""+code.indexOf(text.charAt(len - i - 1))); | |
num = num.add(pos.multiply(pow)); | |
pow = pow.multiply(base); | |
} | |
return num; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment