python struct example
본 포스트는 python의 struct 라이브러리의 api와 사용 예제를 싣고 있다. what is python struct? python의 struct는 c 구조체와 python bytes object 간 상호 변환을 지원하는 라이브러리로, 네트워크 상에서 데이터를 주고받을 때 편하게 사용할 수 있다. c 구조체가 저장되는 메모리 구조와 동일하게 하기 위해 필요시 패딩 바이트가 추가된다. 아래는 c 코드와 python에서의 struct가 저장되는 메모리 크기와 데이터를 비교 예이다. c struct struct test { short a; long b; short c; }; int _tmain(int argc, _TCHAR *argv[]) { test t = { 1, 2, 3 }; int len = sizeof(t); printf("%d\n", sizeof(t)); unsigned char *pt = (unsigned char*)&t; for (int i = 0; i < len; i++) printf("0x%x ", pt[i]); return 0; } 실행 결과 12 0x1 0x0 0xcc 0xcc 0x2 0x0 0x0 0x0 0x3 0x0 0xcc 0xcc python struct import struct pack_format = '@hlh0l' t = struct.pack(pack_format,1,2,3) print(struct.calcsize(pack_format)) print(t) 실행 결과 12 b'\x01\x00 \x00\x00 \x02\x00\x00\x00\x03\x00 \x00\x00 ' python s...