Algorithm/SW Expert Academy

[Python] 5185. 이진수

느낌표 공장장 2021. 9. 30. 17:06
# 16진수 -> 2진수
def hex_to_bin(hexa):
    binary = ''
    for i in hexa:
        x = int(i, 16)  # 10진수 변환
        temp = ''
        # 10진수 -> 2진수 변환
        for _ in range(4):
            x, n = divmod(x, 2)
            temp = str(n) + temp
        binary += temp
    return binary

def hex_to_bin2(n, hexa):
    x = int(hexa, 16)
    for j in range(n-1, -1, -1):
        if x & (2 ** j) == 0:
            print(0, end='')
        else:
            print(1, end='')
    print()


tc = int(input())
for idx in range(1, tc+1):
    n, hexa = input().split()
	
    # 1번 방법 
    print('#{} {}'.format(idx, hex_to_bin(hexa)))
	
    # 2번 방법	# 내장함수 bin 사용
    print('#{} {}'.format(idx, bin(int(hexa, 16))[2:].zfill(int(n)*4)))   
	  
    # 3번 방법   # format 사용
    print('#{} {}'.format(idx, format(int(hexa, 16), 'b').zfill(int(n)*4)))
	
    # 4번 방법	# 비트연산자 사용
    hex_to_bin2(int(n)*4, hexa)

'Algorithm > SW Expert Academy' 카테고리의 다른 글

[Python] 1242. 암호 코드 스캔  (0) 2021.09.30
[Python] 5186. 이진수2  (0) 2021.09.30
[Python] 1240. 단순 2진 암호코드  (0) 2021.09.29
[Python] 5178. 노드의 합  (0) 2021.09.24
[Python] 5177. 이진힙  (0) 2021.09.24