본문 바로가기

파이썬 담아두기

파이썬 Binary 파일값 hex로 다루기

반응형

binascii 모듈을 이용해서 파일에서 읽어온 값을 hex 수준에서 다룰 것이다.


보통 파일을 열어 read(4) 후 print 하면 ascii 수준의 값인 "abcd"가 출력된다.

이를 hex 수준의 값으로 출력하고 싶다면 binascii.b2a_hex() 함수를 이용하면 된다.


뜻을 풀어보면 다음과 같다.

b2a : Binary to Ascii 즉, Binary 값을 Ascii 문자열로 만들건데,

_hex() : 16진수 표현식으로 만들거다.


ex) 시그니처를 검사한다던지, 파일 헤더값을 참조한다던지 등 hex 값을 이용할 일이 많다.


문자열의 hex 값으로 출력이 잘 된다.



binascii.b2a_hex(data)
binascii.hexlify(data)

Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The resulting string is therefore twice as long as the length of data.

binascii.a2b_hex(hexstr)
binascii.unhexlify(hexstr)

Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex()hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise a TypeError is raised.



반응형

'파이썬 담아두기' 카테고리의 다른 글

파이썬3 현재 커서 위치 반환  (0) 2018.09.27
파이썬3 바이너리 값 편집  (0) 2018.09.23
파이썬 한글 인코딩 해결  (0) 2018.09.21
파이썬 입출력  (0) 2018.09.21
파이썬에서 프로세스 생성  (0) 2018.08.21