Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode/decode a long to a string using a fixed set of letters in Java

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.

like image 610
Christian Ullenboom Avatar asked Dec 09 '22 15:12

Christian Ullenboom


1 Answers

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.

Related questions

  • substitution cypher with different alphabet length
like image 103
polygenelubricants Avatar answered Dec 13 '22 22:12

polygenelubricants