public byte[] decode(String encodeString){
if(encodeString == null || (encodeString.length() == 0) || (encodeString.length()) % 4 != 0){
throw new IllegalArgumentException("传入的参数不是正确的base64字符串");
}
int encodeLength = encodeString.length();
byte decodeByte[] = new byte[encodeLength /4 * 3];
int indexPos = 0;
char c = encodeString.charAt(0);
int code = 0;
int pos = 0;
boolean invalidChar = false;
for( int j = 0; c != '=' && j < encodeLength; j++){
pos = pos % 3;
switch (pos){
case 0 :
code = getCharacterPos(c) << 2;
c = encodeString.charAt(j + 1);
if(c != '='){
code = code | (getCharacterPos(c) >> 4);
}
invalidChar = false;
break;
case 1 :
code = getCharacterPos(c) << 4;
c = encodeString.charAt(j + 1);
if(code == 0 && c == '='){
invalidChar = true;
}else if(c != '='){
code = code | getCharacterPos(c)>>2;
}
break;
case 2 :
code = getCharacterPos(c)<< 6;
j++;
c = encodeString.charAt(j);
if(c == '='){
invalidChar = true;
}else{
invalidChar = false;
code = code | getCharacterPos(c);
}
if( j + 1 < encodeLength){
c = encodeString.charAt(j + 1);
}
break;
}
pos ++;
if( ! invalidChar){
decodeByte[indexPos] = (byte)code;
indexPos ++ ;
}
}
byte [] tmp ;
if(encodeLength > indexPos){
tmp = new byte[indexPos];
for(int i = 0; i < indexPos; i++){
tmp[i] = decodeByte[i];
}
}else{
tmp = decodeByte;
}
return tmp;
}
if(encodeString == null || (encodeString.length() == 0) || (encodeString.length()) % 4 != 0){
throw new IllegalArgumentException("传入的参数不是正确的base64字符串");
}
int encodeLength = encodeString.length();
byte decodeByte[] = new byte[encodeLength /4 * 3];
int indexPos = 0;
char c = encodeString.charAt(0);
int code = 0;
int pos = 0;
boolean invalidChar = false;
for( int j = 0; c != '=' && j < encodeLength; j++){
pos = pos % 3;
switch (pos){
case 0 :
code = getCharacterPos(c) << 2;
c = encodeString.charAt(j + 1);
if(c != '='){
code = code | (getCharacterPos(c) >> 4);
}
invalidChar = false;
break;
case 1 :
code = getCharacterPos(c) << 4;
c = encodeString.charAt(j + 1);
if(code == 0 && c == '='){
invalidChar = true;
}else if(c != '='){
code = code | getCharacterPos(c)>>2;
}
break;
case 2 :
code = getCharacterPos(c)<< 6;
j++;
c = encodeString.charAt(j);
if(c == '='){
invalidChar = true;
}else{
invalidChar = false;
code = code | getCharacterPos(c);
}
if( j + 1 < encodeLength){
c = encodeString.charAt(j + 1);
}
break;
}
pos ++;
if( ! invalidChar){
decodeByte[indexPos] = (byte)code;
indexPos ++ ;
}
}
byte [] tmp ;
if(encodeLength > indexPos){
tmp = new byte[indexPos];
for(int i = 0; i < indexPos; i++){
tmp[i] = decodeByte[i];
}
}else{
tmp = decodeByte;
}
return tmp;
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货