Improvement in Base64 (#545)
* Improvement in Base64 Added a private constructor to hide the implicit public one. Modified the switch statement by the 'if' statement to increase readability. Merge 'if' blocks with equal implementations. Extracted the ternary operation nested in an independent declaration. * Removed unnecessary method. Bringing back the braces. Clarifying ternary operation with parentheses.
This commit is contained in:
parent
4f8919e8d5
commit
cb85a0fa35
@ -5,6 +5,7 @@ package com.rarchives.ripme.utils;
|
||||
* From http://stackoverflow.com/a/4265472
|
||||
*/
|
||||
public class Base64 {
|
||||
|
||||
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
|
||||
|
||||
private static int[] toInt = new int[128];
|
||||
@ -15,6 +16,9 @@ public class Base64 {
|
||||
}
|
||||
}
|
||||
|
||||
private Base64() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the specified byte array into Base64 string.
|
||||
*
|
||||
@ -26,6 +30,7 @@ public class Base64 {
|
||||
char[] ar = new char[((size + 2) / 3) * 4];
|
||||
int a = 0;
|
||||
int i = 0;
|
||||
|
||||
while (i < size) {
|
||||
byte b0 = buf[i++];
|
||||
byte b1 = (i < size) ? buf[i++] : 0;
|
||||
@ -37,10 +42,11 @@ public class Base64 {
|
||||
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
|
||||
ar[a++] = ALPHABET[b2 & mask];
|
||||
}
|
||||
switch (size % 3) {
|
||||
case 1: ar[--a] = '=';
|
||||
case 2: ar[--a] = '=';
|
||||
|
||||
if (size % 3 == 1 || size % 3 == 2) {
|
||||
ar[--a] = '=';
|
||||
}
|
||||
|
||||
return new String(ar);
|
||||
}
|
||||
|
||||
@ -51,25 +57,30 @@ public class Base64 {
|
||||
* @return the byte array (not null)
|
||||
*/
|
||||
public static byte[] decode(String s) {
|
||||
int delta = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
|
||||
int delta = s.endsWith("==") ? 2 : (s.endsWith("=") ? 1 : 0);
|
||||
byte[] buffer = new byte[s.length() * 3 / 4 - delta];
|
||||
int mask = 0xFF;
|
||||
int index = 0;
|
||||
|
||||
for (int i = 0; i < s.length(); i += 4) {
|
||||
int c0 = toInt[s.charAt(i)];
|
||||
int c1 = toInt[s.charAt(i + 1)];
|
||||
buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask);
|
||||
|
||||
if (index >= buffer.length) {
|
||||
return buffer;
|
||||
}
|
||||
int c2 = toInt[s.charAt(i + 2)];
|
||||
buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask);
|
||||
|
||||
if (index >= buffer.length) {
|
||||
return buffer;
|
||||
}
|
||||
int c3 = toInt[s.charAt(i + 3)];
|
||||
buffer[index++] = (byte) (((c2 << 6) | c3) & mask);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user