Java 如何将整数转换为 base64 (0-9A-Za-z)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22043451/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:14:20  来源:igfitidea点击:

How to convert integers to base64 (0-9A-Za-z)

javastringcharacter-encodingcompressionbase64

提问by pondigi

I have been trying to reduce the length of the way. I represent some integer ID's in my program. For Example

我一直在努力缩短路的长度。我在我的程序中表示一些整数 ID。例如

2
3
15
26
63
...
151564852

I would like them to be represented as such (0-9A-Za-z only)

我希望他们这样表示(仅限 0-9A-Za-z)

2
3
F
Q
z
...
vDF25a   //For example

The approach I thought of is to have 63 if statements which each of the mappings from 0-63 to 0-z respectively and for anything above 64 do a recursion on the value minus 63.

我想到的方法是有 63 个 if 语句,其中每个从 0-63 到 0-z 的映射分别和高于 64 的任何东西对值减去 63 进行递归。

Needless to say, I think my approach is very flawed and impractical. What would be a more appropriate way of doing it?

不用说,我认为我的方法是非常有缺陷和不切实际的。什么是更合适的方法?



Update:

更新:

Following fge'ssuggestion I've got the encoder to work correctly, however my decode function only works for up-to length 2 strings, in cases where the string is larger the sum becomes erroneous. For example for 3840 to 3845 this is the output

按照fge 的建议,我已经让编码器正常工作,但是我的解码功能仅适用于最长 2 个字符串,在字符串较大的情况下,总和变得错误。例如对于 3840 到 3845,这是输出

// Encoded 
zw
x
zy
zz
100

// Decoded
3840
3841
3842
3843
124         //Invalid decoding

Here is my code for the decode function

这是我的解码功能代码

public static int decode(String value)
{
    String revStr = new StringBuilder(value).reverse().toString();

    int sum = 0;



    for (int i=1; i < revStr.length(); i++)
    {
        for (int j=0; j < ALPHABET.length; j++)
        {
            if (ALPHABET[j] == revStr.charAt(i))
            {
                sum += (ALPHABET.length * j) * i;
                break;
            }
        }
    }

    for (int j=0; j < ALPHABET.length; j++)
    {
        if (ALPHABET[j] == revStr.charAt(0))
        {
            sum += j;
            break;
        }
    }

    return sum;
}

采纳答案by fge

This is not base64; base64 encodes binary data.

这不是 base64;base64 编码二进制数据。

Anyway, you don't need a s*load of ifstatements; use an array:

无论如何,您不需要 as*loadif语句;使用数组:

public final class AlphabetEncoder
{
    private static final char[] ALPHABET = { '0', '1', '2', ...., 'z' };
    private static final int ENCODE_LENGTH = ALPHABET.length;

    public static String encode(int victim)
    {
        final List<Character> list = new ArrayList<>();

        do {
            list.add(ALPHABET[victim % ENCODE_LENGTH]);
            victim /= ENCODE_LENGTH;
        } while (victim > 0);

        Collections.reverse(list);
        return new String(list.toArray(new char[list.size()],
            StandardCharsets.UTF_8);
    }

    public int decode(final String encoded)
    {
        int ret = 0;
        char c;
        for (int index = 0; index < encoded.length(); index++) {
            c = encoded.charAt(index);
            ret *= ENCODE_LENGTH;
            ret += Arrays.binarySearch(ALPHABET, c);
       }
       return ret;
    }
}

NOTE ABOUT THE DECODE FUNCTION: it is possible to use Arrays.binarySearch()here since the alphabet has the nice property of being naturally sorted (0 < 1 < 2 < ... < z). However, a test should probably be added that its return code not be negative!

关于解码功能的注意事项:可以在Arrays.binarySearch()此处使用,因为字母表具有自然排序的良好特性(0 < 1 < 2 < ... < z)。但是,可能应该添加一个测试,它的返回码不是负数!

回答by ctutte

Depending on the language you use, there should already be a module which converts a string from/to base64. Check this other post: Base64 Encoding in Java

根据您使用的语言,应该已经有一个模块可以将字符串从 base64 转换为 base64。查看其他帖子:Java 中的 Base64 编码

回答by Uday Shankar

You can refer to already existing logic for converting from Decimal [0-9] to Hexadecimal conversion present in Integerclass and extend the logic for your Base 64 converison. Refer

您可以参考类中现有的用于从十进制 [0-9] 转换为十六进制转换Integer的逻辑,并扩展 Base 64 转换的逻辑。参考

Integer.toHexString(int i)

This maybe the efficient implementation for conversion.

这可能是转换的有效实现。