Python 2 및 Python 3에서 Int 를 바이트로 변환하는 방법
 
int 에서 bytes 로의 변환은 [bytes 에서 int 로의 변환의 역 동작입니다](/ko/howto/python/how-to-convert-bytes-to-integers/로 변환하는 방법 )는 마지막 HowTo 튜토리얼에서 소개되었습니다. 이 기사에서 소개 한 대부분의 int-to-bytes 메소드는 bytes-to-int 메소드의 역 메소드입니다.
Python 2.7 및 3 호환 int에서 bytes로의 변환 방법
    
Python struct module에서 pack 함수를 사용하여 정수를 특정 형식의 바이트로 변환 할 수 있습니다.
>>> import struct
>>> struct.pack("B", 2)
'\x02'
>>> struct.pack(">H", 2)
'\x00\x02'
>>> struct.pack("<H", 2)
'\x02\x00'
struct.pack 함수의 첫 번째 인수는 바이트 길이, 부호, 바이트 순서 (little 또는 big endian) 등과 같은 바이트 형식을 지정하는 형식 문자열입니다.
파이썬 3 int 에서 bytes 로의 변환 방법
int 를 bytes 로 변환하려면 bytes 를 사용하십시오
마지막 기사에 표시된 것처럼 bytes 는 Python 3의 내장 데이터 형식입니다. bytes 를 사용하여 정수 0 ~ 255를 바이트 데이터 유형으로 쉽게 변환 할 수 있습니다.
>>> bytes([2])
b'\x02'
정수는 괄호로 묶어야합니다. 그렇지 않으면, 널 바이트로 초기화 된 매개 변수에 의해 주어진 크기의 바이트 오브젝트를 얻을 수 있지만 해당 바이트는 아닙니다.
>>> bytes(3)
b'\x00\x00\x00'
int.to_bytes()메소드를 사용하여 int 를 bytes 로 변환
Python3.1부터 새로운 정수 클래스 메소드 int.to_bytes()가 도입되었습니다. 마지막 기사에서 논의한 int.from_bytes()의 역변환 방법입니다.
>>> (258).to_bytes(2, byteorder="little")
b'\x02\x01'
>>> (258).to_bytes(2, byteorder="big")
b'\x01\x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'\x02\x01\x00\x00'
>>> (-258).to_bytes(4, byteorder="little", signed=True)
b'\xfe\xfe\xff\xff'
첫 번째 인수는 변환 된 바이트 데이터 길이이고, 두 번째 인수 인 byteorder는 바이트 순서를 리틀 또는 빅 엔디안으로 정의하고 선택적 인수 인 signed는 2의 보수가 정수를 나타내는 데 사용되는지 여부를 결정합니다.
성능 비교
파이썬 3에서는 int 를 bytes 로 변환하는 3 가지 방법이 있습니다.
- bytes()메소드
- struct.pack()메소드
- int.to_bytes() 메소드
각 메소드의 실행 시간을 확인하여 성능을 비교하고 마지막으로 코드 실행 속도를 높이려면 권장 사항을 제공합니다.
>>> import timeint
>>> timeit.timeit('bytes([255])', number=1000000)
0.31296982169325455
>>> timeit.timeit('struct.pack("B", 255)', setup='import struct', number=1000000)
0.2640925447800839
>>> timeit.timeit('(255).to_bytes(1, byteorder="little")', number=1000000)
0.5622947660224895
| 변환 방법 | 실행 시간 (백만 번) | 
|---|---|
| bytes() | 0.31296982169325455 초 | 
| struct.pack() | 0.2640925447800839 초 | 
| int.to_bytes() | 0.5622947660224895 초 | 
따라서 파이썬 2 브랜치에서 이미 소개되었지만 struct.pack()함수를 사용하여 최상의 실행 성능을 얻기 위해 int-to-bytes 변환을 수행하십시오.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook