본문 바로가기

알고리즘/Python

[Python | SWEA] 1928. Base64 Decoder

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&contestProbId=AV5PR4DKAG0DFAUq&categoryId=AV5PR4DKAG0DFAUq&categoryType=CODE&problemTitle=&orderBy=PASS_RATE&selectCodeLang=PYTHON&select-1=2&pageSize=10&pageIndex=1 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

문제


다음과 같이 Encoding 을 한다.

1. 우선 24비트 버퍼에 위쪽(MSB)부터 한 byte씩 3 byte의 문자를 집어넣는다.
2. 버퍼의 위쪽부터 6비트씩 잘라 그 값을 읽고, 각각의 값을 아래 [표-1] 의 문자로 Encoding 한다.


입력으로 Base64 Encoding 된 String 이 주어졌을 때, 해당 String 을 Decoding 하여, 원문을 출력하는 프로그램을 작성하시오.

 

 

제출 답안

decode = ['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','+','/'
      ]

t = int(input())
for i in range(1, t + 1) :
    word = list(input())
    value = ''
    for j in range(len(word)) :
        num = decode.index(word[j])
        bin_num = str(bin(num)[2:])

        while len(bin_num) < 6 :
            bin_num = '0' + bin_num
        value += bin_num

    result = ''
    for j in range(len(word)*6 // 8) :
        data = int(value[j*8 : j*8+8], 2)
        result += chr(data)

    print('#%d %s' % (i, result))

 

개선 답안

파이썬 base64 라이브러리 사용

from base64 import b64decode
 
T = int(input())
 
for tc in range(1, T + 1):
 
    word = input()
    res = b64decode(word).decode('UTF-8')
 
    print('#{} {}'.format(tc,res))

 

참고 자료

https://swbeginner.tistory.com/entry/SWEA-%EC%BD%94%EB%94%A9-Base64-Decoder-PYTHON-1928

 

[SWEA 코딩] Base64 Decoder - PYTHON #1928

소스 코드(라이브러리 X) T = int(input()) # 표 1 decode = ['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'

swbeginner.tistory.com