Python: to_bytes, to_bytes big endian e little endian byte e conversão numérica

gramática

int.to_bytes(length, byteorder)

parâmetro:

  • comprimento – comprimento desejado da matriz (bytes)
  • byteorder – Ordem de bytes usada para converter int em array de bytes.
    • Os valores Endian podem ser “pequenos”, onde o bit mais significativo é armazenado no final e o bit menos significativo é armazenado no início;
    • Também pode ser grande, onde o MSB é armazenado no início e o LSB no final.

anormal:

Se o valor inteiro não for grande o suficiente para caber no comprimento da matriz, um OverflowError será retornado.

num = 1
print(num.to_bytes(length=8, byteorder='little'))
# b'\x01\x00\x00\x00\x00\x00\x00\x00'

print(num.to_bytes(length=8, byteorder='big'))
# b'\x00\x00\x00\x00\x00\x00\x00\x01'
little_byte = b'\x01\x00\x00\x00\x00\x00\x00\x00'
print(int.from_bytes(little_byte, byteorder='little'))
# 1

big_byte = b'\x00\x00\x00\x00\x00\x00\x00\x01'
print(int.from_bytes(big_byte, byteorder='big'))
# 1

おすすめ

転載: blog.csdn.net/mouday/article/details/135045548