基数 > Character.MAX_RADIX 的 Java 数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5803454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java numbers with radix > Character.MAX_RADIX
提问by Lukas Eder
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
我有一个五个字符的字符串,我想将这五个字符用作 ASCII 编码(可打印)数字。实现这一目标的最简单方法是使用
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 andupper-case letters, I'd get a max radix of 62
and the highest encodable number is 62^5 - 1 = 916 132 831
.
这会给我从"0"
到的数字"zzzzz"
。可惜Long.toString(int, int)
只支持小写字母,不支持大写字母。这意味着最大基数是36
,我可以编码的最高数字是36^5 - 1 = 60 466 175
. 如果我可以同时使用小写和大写字母,我将得到最大基数62
和最高可编码数是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?
除了复制Long
的源代码和扩展可能的数字之外,还有其他地方我应该研究一下,首先,这已经实现了吗?
采纳答案by Stephen C
You don't specify whether or not the characters need to be printableASCII:
您没有指定字符是否需要是可打印的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
.
如果他们这样做,那么你可以去
95^5
。从空格 (SP) 到波浪号 (~),共有 95 个可打印的 ASCII 字符。如果他们没有,那么你可以去
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.)
无论哪种方式,进行转换的算法都很简单,并且比扩展到Long.toString(...)
. (您大概不必担心字符<->
数字映射中的符号、范围错误或漏洞。从头开始编码会更容易。)
However, I'm not aware of any existingimplementation of extended radix numbers.
但是,我不知道扩展基数的任何现有实现。
回答by WhiteFang34
If you're willing to go two characters beyond alphanumeric you could use Base64encoding.
如果您愿意使用字母数字以外的两个字符,则可以使用Base64编码。
Using Base64
from Apache Commons Codecyou could get 1073741824 possible values like this:
使用Base64
来自Apache的百科全书编解码器,你可以得到这样1073741824个可能的值:
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);