Python Binary

This tutorial provide explanations on bytes(), bytearray(), and memoryview() with examples.

Python Bytes

bytes() returns a bytes object, namely converting objects into bytes objects. Bytes objects are immutable sequences. The following is the syntac of bytes().

Syntax : bytes(x, encoding, error)

  • x : The source object to be converted.
  • encoding: If x is a string, the encoding is required.
  • error : Specify what to do in case the conversion fails.
hello="hello world"

The following is the output.

b'hello world'

The following is the output.


Python bytearray

Different from bytes() that returns an immutable object (i.e., cannot be modified), bytearray() returns an object that is immutable.

bytearray("hello world","utf-8")
bytearray(b'hello world')

Python memoryview

In short, memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.

b_0=bytearray("hello world","utf-8")
<memory at 0x000001F1EDBD4700>

Note that, I admit that the discussion about “memoryview” is insufficient here. Please refer to a discussion on Stackoverflow on this topic.