파이썬이 정말 만능인 것 같다.
아주 단순하게 빠르게 내가 원하는 기능은 다 있다. 특히 struct 라이브러리를 이용하면 쉽게 UART 프로토콜을 맞출 수가 있어서 편리하다.
https://docs.python.org/2/library/struct.html
7.3. struct — Interpret strings as packed binary data — Python 2.7.16 documentation
7.3. struct — Interpret strings as packed binary data This module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data stored in files or from network connections, among other sour
docs.python.org
1. endian 처리를 쉽게 할 수 있다. '<', '>' 옵션참고 그리고 이러한 문자를 넣게되면 PAD Byte를 제거한다.
PAD byte? 메모리를 채워주는 바이트 => 찾아보면 많이 나온다. 연산량을 줄이기 위한 메모리 설정법임.
2. 적분규칙이 있어서 'BBBB' = '4B' 동일 효과
3. struct로 뭉치고 싶은 타입을 지정해 줄 수 있어서 좋다.
2바이트라면 format에서 h(short)만 해줘도 된다.
4. pack 예제
>>> import struct
>>> temp1 = 1
>>> temp2 = 2
>>> temp3 = 3
>>> temp4 = 4
>>> packed_data = struct.pack('<4B', temp1, temp2, temp3, temp4)
>>> packed_data
'\x01\x02\x03\x04'
5. pack_into 예제
기존 버퍼에 추가시키기
>>> temp5 = 5
>>> temp6 = 6
>>> msg_buff = bytearray(2)
>>> struct.pack_into('<2B',msg_buff,0,temp5,temp6)
>>> msg_buff
bytearray(b'\x05\x06')
'Code > Python' 카테고리의 다른 글
[python]PDF => TXT 추출 (0) | 2019.04.21 |
---|