将base64字符串转换为十进制时出错

时间:2019-05-05 00:07:54

标签: java base64 tobase64string

下面的方法将十进制转换为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)。

有什么主意吗?

1 个答案:

答案 0 :(得分: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);
}