Pat*_*ogt 7 java string algorithm biginteger base36
目前我正在使用一种算法将一个普通字符串编码为Base36字符串.
我尝试了以下但它不起作用.
public static String encode(String str) {
return new BigInteger(str, 16).toString(36);
}
Run Code Online (Sandbox Code Playgroud)
我想这是因为字符串不仅仅是十六进制字符串.如果我使用字符串"Hello22334!" 在Base36,然后我得到了NumberFormatException
.
我的方法是将每个字符转换为数字.将数字转换为十六进制表示,然后将hexstring转换为Base36.
我的方法是否正常还是有更简单或更好的方法?
Chr*_*röm 12
首先,您需要将字符串转换为数字,由一组字节表示.这是你使用编码的.我强烈推荐UTF-8.
然后,您需要将该数字,字节集转换为字符串,基数为36.
byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
String base36 = new BigInteger(1, bytes).toString(36);
Run Code Online (Sandbox Code Playgroud)
要解码:
byte[] bytes = new Biginteger(base36, 36).toByteArray();
// Thanks to @Alok for pointing out the need to remove leading zeroes.
int zeroPrefixLength = zeroPrefixLength(bytes);
String string = new String(bytes, zeroPrefixLength, bytes.length-zeroPrefixLength, StandardCharsets.UTF_8));
Run Code Online (Sandbox Code Playgroud)
private int zeroPrefixLength(final byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != 0) {
return i;
}
}
return bytes.length;
}
Run Code Online (Sandbox Code Playgroud)