1 개요[ | ]
- SWEA 1928 Base64 Decoder
# | 문제 | 풀이 |
---|
Java같은 경우에는 라이브러리로 간단히 풀었는데, C++로는 decoder를 직접 구현해야 하는군요. 비트 연산에 익숙해질 필요가 있겠습니다. 다행히(?) 본 문제에서는 4로 나누어 떨어지는 입력만 있기 때문에 padding 처리는 하지 않아도 됩니다.
- base64 인코딩: 8비트×3글자 → 6비트×4글자로 변환
- base64 디코딩: 6비트×4글자 → 8비트×3글자로 변환
'base64'는 말그대로 '64진수(6비트=2^6=64)'로 변환한다는 의미입니다. base64 인코딩을 하는 이유는 여러 가지가 있겠지만... 바이너리를 직접 표시하면 읽을 수 없는 문자들(예: 제어문자)이 있는데, 읽을 수 있는 문자(알파벳/숫자/기호)로 바꿔 준다는 장점이 있습니다. URL 파라미터로 처리하는 것도 간편해지고요. 단점이라면 3글자를 4글자로 바꾸므로 크기가 33% 정도 증가한다는 점이 있습니다.
2 C++[ | ]
C++
Copy
#include <iostream>
using namespace std;
int m[128];
void init() {
for(int i=0; i<26; i++) m['A'+i]=i;
for(int i=0; i<26; i++) m['a'+i]=26+i;
for(int i=0; i<11; i++) m['0'+i]=52+i;
m['+'] = 62;
m['/'] = 63;
}
void decode(char* src, char* dst) {
int bits, pos=0, pos2=0;
while(src[pos]) {
bits = m[src[pos++]] << 18;
bits += m[src[pos++]] << 12;
bits += m[src[pos++]] << 6;
bits += m[src[pos++]];
dst[pos2++] = bits>>16 & 0xFF;
dst[pos2++] = bits>>8 & 0xFF;
dst[pos2++] = bits & 0xFF;
}
dst[pos2] = 0;
}
int main() {
init();
int T;
scanf("%d", &T);
char encoded[100000];
char decoded[100000];
for(int tc=1; tc<=T; tc++) {
scanf("%s", encoded);
decode(encoded, decoded);
printf("#%d %s \n", tc, decoded);
}
}
3 Java[ | ]
Java
Copy
import java.util.Scanner;
import java.util.Base64;
public class Solution {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int t=1; t<=T; t++) {
String encoded = sc.next();
String decoded = new String(Base64.getDecoder().decode(encoded));
System.out.format("#%d %s\n", t, decoded);
}
}
}
4 Python[ | ]
Python
Copy
from base64 import b64decode
T = int(input())
for t in range(1, T+1):
print(f'#{t} {b64decode(input()).decode("UTF-8")}')
# https://www.github.com/wansang93/Algorithm
편집자 Jmnote Wansang93 Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.