본문 바로가기
Python

[Python] bytes and bytearray: Binary Data for Python

by ds31x 2024. 1. 15.

Python에서 bytesbytearray
binary data를 byte 단위 (1byte = 8bit)로 다루는데
사용되는 Data Type임.

bytes:

  • bytesimmutable byte sequence 로서 일종의 byte로 구성된 tuple에 해당 함.
  • byte literal은 다음과 같이 b라는 prefix를 사용함.
    • b'Hello''Hello'라는 문자열에 대한 byte literal을 의미함.
    • 문자열에 대한 bytes 이므로 encoding이 사용되며 기본으로 utf8이 사용됨.
    • byte literal과 같이 추후 변경이 되지 않는 binary data를 위한 데이터 타입이 bytes임.
  • bytes 객체를 출력할 경우,
    • utf8인 경우에는 ascii에 해당하는 바이트는 ascii 문자로 출력되고
    • ascii에 해당하지 않는 1바이트는 hex sequence 로 표현함 (backslash \x를 통해 hex, 16진법을 사용함을 표시하고, 2개의 숫자로 1byte를 표현)
    • utf16등의 encoding을 사용한 경우에는
    • hex sequence로 표현된다.

다음의 코드와 출력 결과를 위의 설명과 함께 참고할 것.

s = 'Hello'

b = s.encode('utf8')
print(type(b), b)
print(b'Hello' == b)
b = s.encode('utf16')
print(type(b), b)

 

결과는 다음과 같음.

<class 'bytes'> b'Hello'
True
b'Hello'
<class 'bytes'> b'\xff\xfeH\x00e\x00l\x00l\x00o\x00'

 

literal 용어가 익숙치 않다면 다음을 참고.

https://dsaint31.tistory.com/462

 

[Basic] Literal

소스 코드 상에서 고정된 값을 가르킴. (또는 고정된 값을 나타내는 표기법을 의미함.) Programming language에서 data의 값을 지정(specifying data values)하는 방법은 다음 중의 하나임. Literal을 사용. Variable

dsaint31.tistory.com


bytearray:

  • bytearraymutable byte sequence 로서 일종의 byte로 구성된 list.
    • bytearray(b'Hello') 를 통해
    • 'Hello'의 utf8 인코딩에 해당하는 bytes 객체를 기준으로 bytearray로 변환.
  • 해당 bytesarray는 변경가능함.
    • arr = bytearray(b'Hello') 를 수행하고
    • arr[0] = b'J'와 같은 코드를 수행하면
    • arrb'Jello'로 변경됨.

참고할 것.

Python에서 디코딩은 특정 인코딩방식에 따라 bytesstr로 변경하는 것을 의미하고, 인코딩은 str로부터 bytes를 얻어내는 것을 가르킴.

기본적으로는 utf8을 사용함.

  • str 객체의 경우 encode 메서드를 통해 encoding방식에 따른 bytes를 얻을 수 있음 (기본은 utf8이나 asciiutf16등을 지정가능함).
  • bytes 또는 bytearray 객체는 decode 메서드를 통해 특정 encoding 방식에 따른 해당하는 str을 얻을 수 있음.
    • 만약 decoding시 적용하는 encoding 방식에 지정되지 않은 바이트값이 있는 경우, 에러가 발생함.
    • errors='ignore'을 인자로 주면 에러를 무시하고 변환.

다음 예를 참고할 것.

np_c = bytes([128])
np_c_str = np_c.decode('ascii',errors='ignore')
np_c1 = bytes([129])
np_c1_str = np_c.decode('ascii',errors='ignore')

with open('bin2txt.txt', 'wb') as f:
    f.write('a'.encode('ascii'))
    f.write(np_c)
    f.write(np_c1)
    f.write('b'.encode('ascii'))

null_c = bytes([0])
null_str = null_c.decode('ascii', errors='ignore')

# encoding에 정의되지 않은 bytes들은 text 에서 일종의 빈 문자 등으로 처리해버림.
# decode에서 errors='strict' 로 주어질 경우 아예 decode가 되지 않게도 할 수 있으나,
# 많은 앱에선 일종의 null처럼 처리해버림. (단 null과 같진 않은 경우가 대부분.)
print(f"[{np_c_str}], [{np_c1_str}], {np_c_str == np_c1_str}")


print(f"[{np_c_str}], [{null_str}], {np_c_str == null_str}")

 

결과는 다음과 같음.

[], [], True
[], [], False

같이 읽어보면 좋은 URLs

2024.01.15 - [Python] - [python] Text mode vs. Binary mode: File open

 

[python] Text mode vs. Binary mode: File open

Python에서 특정 파일을 open하는 경우, text mode 또는 binary mode 중 하나로 열게 된다. 이 둘의 차이점은 간단히 설명하면, 현재 open하고자 하는 file을 text파일로 처리할지 아니면 binary파일로 처리할지

ds31x.tistory.com

https://dsaint31.me/mkdocs_site/CE/ch01/code_for_character/#encodings-for-unicode

 

BME228

Codes for Characters Code란 특정 형태의 inforamtion을 다른 방법으로 표현하는 규칙 또는 해당 규칙으로 표현된 결과물을 가르킴. 문자를 나타내기 위한 code는 인간이 사용하는 문자를 일종의 기호 또는

dsaint31.me

 

반응형