SMALL
할 때마다 검색하는 나란 개발자...
이 참에 정리해두자.
아래 string은 말그대로 hex string이다. hex값을 string형태로 가지고 있음.
이를 byte 형태로 변환하는 코드
str1 = '0x0A'
str2 = '0A'
# 먼저 integer의 형태로 변환
hexint = int(str1, 16)
print(hexint)
# integer to byte
print(bytes([hexint]))
# 한번에 하기
print(bytes([int(str1, 16)]))
# str2도.
print(bytes([int(str2, 16)]))
문자열을 숫자로 변환한다고 생각하면 쉽다. 16진수 숫자로 변환하는 것이다.
다음으로 int를 byte로 변환하면 된다.
출력:
10
b'\n'
b'\n'
b'\n'
그럼~~~ hex가 여러개 나열된 string일 경우에는!
str3 = '59 5A'
bytearr = bytes(list(map(lambda x: int(x, 16), str3.split(' '))))
print(bytearr)
split을 하여 각자 list화한 다음, map 함수를 이용해 int로 변환한다.
다만 int함수에 인자가 두 개 들어가므로, lambda를 이용해주면 깔끔하게 변환된다.
출력:
b'YZ'
LIST
'개발Study > python' 카테고리의 다른 글
pip 패키지 설치 시간 단축시키기 (0) | 2023.09.07 |
---|---|
python lambda (0) | 2021.03.21 |
python 소멸자 (0) | 2021.03.11 |
Python에서의 Multiprocessing (0) | 2021.03.09 |
댓글