0

下面的方法将小数转换为BASE64字符串:

public static String id2base64String(String mediaId) {
    String postId = "";
    try {
        long id = Long.parseLong(mediaId);
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

        while (id > 0) {
            long remainder = (id % 64);
            id = (id - remainder) / 64;
            postId = alphabet.charAt((int) remainder) + postId;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(String.format("input is %s, output is %s", mediaId, postId));
    return postId;
}

我编写了一个方法来反转函数,以便它可以将BASE64字符串转换为小数:

public static String base64StringToId(String base64String) {
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    long id = 0L;
    for (int i = 0; i < base64String.length(); i++) {
        char c = base64String.charAt(i);
        int i1 = alphabet.indexOf(c);
        id += i1 * Math.pow(64, base64String.length() - 1 - i);
        //converted[string.length() - i - 1] = i1;
    }
    System.out.println(String.format("input is %s, output is %s", base64String, String.valueOf(id)));
    return String.valueOf(id);
}

使用以下代码运行时:

    String base64String = "ybyPRoQWzX";
    String id = "908540701891980503";
    id2base64String(id);
    base64StringToId(base64String);

它显示输出为:

input is 908540701891980503, output is ybyPRoQWzX
input is ybyPRoQWzX, output is 908540701891980544

如您所见,第二种方法的输出不如预期(预期是908540701891980503,但我得到了908540701891980544)。

任何想法?

4

1 回答 1

1

大数的浮点运算有一个小错误。我认为这样写会更加一致。

public static String base64StringToId(String base64String) {
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    long id = 0L;
    for (int i = 0; i < base64String.length(); i++) {
        char c = base64String.charAt(i);
        int i1 = alphabet.indexOf(c);
        id = (id * 64) + i1;
        //id += i1 * Math.pow(64, base64String.length() - 1 - i);
        //converted[string.length() - i - 1] = i1;
    }
    System.out.println(String.format("input is %s, output is %s", base64String, String.valueOf(id)));
    return String.valueOf(id);
}
于 2019-05-05T00:30:10.703 回答