-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathBase36.java
More file actions
41 lines (35 loc) · 1.12 KB
/
Base36.java
File metadata and controls
41 lines (35 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package io.multibase;
import java.math.BigInteger;
public class Base36 {
public static byte[] decode(String in) {
byte[] withoutLeadingZeroes = new BigInteger(in, 36).toByteArray();
int zeroPrefixLength = zeroPrefixLength(in);
byte[] res = new byte[zeroPrefixLength + withoutLeadingZeroes.length];
System.arraycopy(withoutLeadingZeroes, 0, res, zeroPrefixLength, withoutLeadingZeroes.length);
return res;
}
public static String encode(byte[] in) {
String withoutLeadingZeroes = new BigInteger(1, in).toString(36);
int zeroPrefixLength = zeroPrefixLength(in);
StringBuilder b = new StringBuilder();
for (int i = 0; i < zeroPrefixLength; i++) b.append("0");
b.append(withoutLeadingZeroes);
return b.toString();
}
private static int zeroPrefixLength(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != 0) {
return i;
}
}
return bytes.length;
}
private static int zeroPrefixLength(String in) {
for (int i = 0; i < in.length(); i++) {
if (in.charAt(i) != '0') {
return i;
}
}
return in.length();
}
}