Post

(python) binary data와 16진수 / struct.pack

binary data

hex, bin
1
2
3
hex = 0xf1
bin = 0b11110001

unicode / bytes 변환 int to ascii

문자열을 bytes로 형변환 하고 싶다면 이 방법이 제일 간단하기는 하다.

1
2
a = b'string to byte'

b ‘\x80’ 으로 직접 지정하면 \x80 이상 data도 입력할 수 있다.

1
2
3
hex(ord('a')) #unicode -> byte
chr(0x61)     #byte    -> unicode

ord는 설명으로는 ASCII 변환이라고 써있기는 하지만 \x81같은 데이터를 넘겨도 잘 동작한다.

struct.pack

binary data를 little endian으로 정렬 할 때는 struct module을 사용하면 편하다.

1
2
struct.pack(fmt, v1, v2, ...)

fmt 의 첫 번째 문자로는 byte order, size, alignment를 지정할 수 있다. ‘<’ 를 지정하면little-endian으로 정렬 해준다. 두 번째 문자 부터는Format characters ( 변수의 type )을 지정할 수 있다. 자주 쓰는 건 unsigned long인 ‘L’ 이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import struct

  

def p32(x): return struct.pack('<L', x)
def u32(x): return struct.unpack('<L', x)[0] # 투플로 반환되니 반드시 [0] 써주어야 한다.

  

def p8(x): return pack('B', x)
def p64(x): return pack('<Q', x)
sfp = 0xfeffe0e0
print(L(sfp))

==============
b'\xe0\xe0\xff\xfe'

(void *) 크기로 맞추기
1
2
addr.ljust(8, "\x00")

원래 ljust()는 문자열을 왼쪽으로 정렬하기 위한 함수이나, 이렇게 응용할 수 있다.

This post is licensed under CC BY 4.0 by the author.