Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java numbers with radix > Character.MAX_RADIX

I have a five-character String and I want to use those five characters as an ASCII-encoded (printable) number. The simplest way to achieve this is to use

Long.toString(number, Character.MAX_RADIX);

This will give me numbers from "0" to "zzzzz". Unfortunately Long.toString(int, int) only supports lower-case letters, no upper-case letters. This means that the max radix is 36 and the highest number I can encode is 36^5 - 1 = 60 466 175. If I could use both lower and upper-case letters, I'd get a max radix of 62 and the highest encodable number is 62^5 - 1 = 916 132 831.

Apart from copying Long's source code and extending the possible digits, is there any other place I should look into, first, where this is already implemented?

like image 482
Lukas Eder Avatar asked Apr 27 '11 11:04

Lukas Eder


1 Answers

If you're willing to go two characters beyond alphanumeric you could use Base64 encoding.

Using Base64 from Apache Commons Codec you could get 1073741824 possible values like this:

byte bytes[] = new byte[4];
bytes[0] = (byte) ((value >> 24) & 0xFF);
bytes[1] = (byte) ((value >> 16) & 0xFF);
bytes[2] = (byte) ((value >> 8) & 0xFF);
bytes[3] = (byte) (value & 0xFF);
String encoded = Base64.encodeBase64String(bytes).substring(1, 6);
like image 87
WhiteFang34 Avatar answered Sep 25 '22 13:09

WhiteFang34