如何在一个字符串中打包 2 个长值并将它们取回

How to pack 2 long values in one single string and get them back

请帮我出出主意,我怎么能在Java中做到这一点:

输入:

long id1 = 123456 (any long value)
long id2 = 4490390904 (any long value)

输出:

a94dhjfh4990-d49044 (whatever, any string)

然后,根据输出取回id1id2。所以,某种编码,散列。不是很明显(例如 123456###4490390904),但我也不想要加密级别...
只是想知道 Java 库(所以没有第 3 方库)或一些算法(代码片段)是否已经提供了我可以使用的东西。

更新 类似于:https://github.com/peet/hashids.java

如果它只是任何字符串,那么你可以简单地这样做:

Long a,b;
a=...; b=...;
//coding
String s = a + "#" + b;
//decoding
ab= a.split(s,'#');
System.out.println("a= " + Long.parsLong(ab[0]));
System.out.println("b= " + Long.parsLong(ab[1]));

同时您可以使用 SHA-1 explained here 对中间字符串进行编码

瞎打,因为你的要求不是很准确。下面提供了 2 个函数,用于 encode String 中的值和 decode StringString 的数组中=13=]。每个 long 值都采用十六进制格式。

public class IdEncoder {

    static final String sep = "-";

    public static String encode(long id1, long id2) {
        return Long.toHexString(id1)+sep+Long.toHexString(id2);
    }

    // Assume the paramater is at the right format.
    // Several exceptions can be thrown. Add exception handling as necessary...
    public static long[] decode(String id) {
        String[] ids = id.split(sep);
        long[] idl = new long[2];
        idl[0] = Long.parseUnsignedLong(ids[0], 16);
        idl[1] = Long.parseUnsignedLong(ids[1], 16);
        return idl;
    }

    public static void main(String[] args) {

        String ids = encode(123456, 675432187);
        System.out .println(ids);
        long[] idl = decode(ids);
        System.out .println(Arrays.toString(idl));
    }
}

打印

1e240-284246fb
[123456, 675432187]

这就是我要找的: https://github.com/peet/hashids.java

抱歉,如果我的要求不够准确。