Given an arbitrary set of letters
String range = "0123456789abcdefghijklmnopABCD#";
I am looking for 2 methods to encode/decode from long <-> String
String s = encode( range, l );
and
long l = decode( range, s );
So decode(range, encode(range, 123456789L)) == 123456789L
And if range is "0123456789" thats the usual way of encoding.
The following code does what you need:
static long decode(String s, String symbols) {
final int B = symbols.length();
long num = 0;
for (char ch : s.toCharArray()) {
num *= B;
num += symbols.indexOf(ch);
}
return num;
}
static String encode(long num, String symbols) {
final int B = symbols.length();
StringBuilder sb = new StringBuilder();
while (num != 0) {
sb.append(symbols.charAt((int) (num % B)));
num /= B;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
String range = "0123456789abcdefghijklmnopABCD#";
System.out.println(decode(encode(123456789L, range), range));
// prints "123456789"
System.out.println(encode(255L, "0123456789ABCDEF"));
// prints "FF"
System.out.println(decode("100", "01234567"));
// prints "64"
}
Note that this is essentially base conversion with a custom set of symbols.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With