I have an array of bytes (any length), and I want to encode this array into string using my own base encoder. In .NET
is standard Base64
encoder, but w
Here is the sample code snippet to convert byte array to base64. There is a very good article on this, I took reference from this.
public class Test {
private static final char[] toBase64URL = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
};
public static void main(String[] args) {
byte[] mess = "ABC123".getBytes();
byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
StringBuilder builder = new StringBuilder();
for(int i = 0; i < mess.length; i++) {
for (byte m : masks) {
if ((mess[i] & m) == m) {
builder.append('1');
} else {
builder.append('0');
}
}
}
System.out.println(builder.toString());
int i =0;
StringBuilder output = new StringBuilder();
while (i < builder.length()){
String part = builder.substring(i, i+6);
int index = Integer.parseInt(part, 2);
output.append(toBase64URL[index]);
i += 6;
}
System.out.println(output.toString());
}
}