开发者

Java numbers with radix > Character.MAX_RADIX

开发者 https://www.devze.com 2023-03-01 04:44 出处:网络
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

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 开发者_Go百科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?


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);


You don't specify whether or not the characters need to be printable ASCII:

  • If they do, then you can go to 95^5. There are 95 printable ASCII characters from space (SP) to tilde (~).

  • If they don't, then you can go to 128^5 == 2^35.

Either way, the algorithm for doing the conversion is straightforward, and is simpler than an extension to Long.toString(...). (You presumably don't have to worry about signs, range errors, or holes in the character <-> digit mapping. It would be easier to code this from scratch.)

However, I'm not aware of any existing implementation of extended radix numbers.

0

精彩评论

暂无评论...
验证码 换一张
取 消