下面的方法将小数点转换为 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
(。
有什么想法?
浮点操作的误差很小。我认为以这种方式写作会变得更加一致。
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);
}