DEV Community

codemee
codemee

Posted on

Little or Big endian 順序

Python 中若是要將整數存入檔案,可以使用整數的 to_bytes 方法轉成位元組序列,再存入檔案,不過要注意的是,轉成位元組序列時會有位元組順序的問題,你可以指定高位元組先(big endian,預設)還是低位元組先(little endian)的順序,例如:

>>> big = (102).to_bytes(2, 'big')
>>> big.hex()
'0066'

>>> big[0]
0

>>> big[1]
102

>>> little = (102).to_bytes(2, 'little')
>>> little.hex()
'6600'

>>> little[0]
102

>>> little[1]
0
Enter fullscreen mode Exit fullscreen mode

由於我們把整數轉成使用 2 個位元組的序列,所以位元組順序不同,就會得到不同的結果,big endian 順序意思是位元組序列從低位元組開始擺放原本整數中從高位元組開始的資料;little endian 則是相反。

如果錯把 big endian 順序的位元組序列當成 little endian 順序的序列,反解為整數時就會出錯,例如:

>>> int.from_bytes(big, 'big')
102

>>> int.from_bytes(big, 'little')
26112

>>> int.from_bytes(little, 'little')
102

>>> int.from_bytes(little, 'big')
26112
Enter fullscreen mode Exit fullscreen mode

所以當你要透過檔案或是其他媒介交換整數資料時,一定要先確定資料的擺放順序,才不會出錯。

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay