搜尋此網誌

2026年4月21日星期二

Bytes Object in Python

In Python, a bytes object is an immutable sequence of integers in the range 0–255, used to represent raw binary data. It’s similar to a string, but instead of characters, it stores bytes.

Immutable: Once created, it cannot be modified (like str).

When you see a b prefix in Python output, it means the object is a bytes literal — raw binary data rather than a regular string.

UTF-8 is the most widely used character encoding today, representing every Unicode character using 1–4 bytes. It is backward-compatible with ASCII, meaning the first 128 characters (like English letters and digits) are encoded exactly the same as ASCII.

Name: Unicode Transformation Format – 8-bit.

Type: Variable-length encoding (1 to 4 bytes per character).

A bytearray in Python is very similar to a bytes object, but with one key difference: it is mutable. That means you can change its contents after creation, unlike bytes which are immutable.

In Python, string slice notation lets you extract parts of a string (substrings).

Hexadecimal (often shortened to “hex”) is a base-16 numbering system. Instead of using only digits 0–9 like decimal (base-10), it uses 16 symbols:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Compact: Easier to read than long binary strings.

Direct mapping: Each hex digit = exactly 4 bits (a “nibble”).

Common uses: Memory addresses, color codes (#FF0000 = red), encoding binary data, debugging.

# Decimal to hex print(hex(255)) # 0xff # Hex to decimal print(int("ff", 16)) # 255 # Binary ↔ Hex print(bin(0xff)) # 0b11111111 print(hex(0b1010)) # 0xa

x in 0xff

In 0xff, the 0x prefix is Python’s (and many other languages’) way of saying: “this number is written in hexadecimal (base‑16)”.

Microsoft Copilot

沒有留言:

發佈留言