如何在 Python 中转换原始大端值

如何在 Python 中转换原始大端值

PSD 文件将大多数二进制字段以大端字节序存储。当您需要自行解码原始字段时,例如从图像资源的原始字节中——BigEndianBitConverter 可以直接从字节数组读取大端 32 位整数。

分步指南

步骤 1:安装包

git clone https://github.com/aspose-psd-foss/Aspose.PSD-FOSS-for-Python.git
cd Aspose.PSD-FOSS-for-Python
# No packaging manifest is published yet -- run from this folder,
# or add it to PYTHONPATH:
export PYTHONPATH=$PWD:$PYTHONPATH

步骤 2:导入所需类

from aspose_psd_foss.psdimage import PsdImage
from aspose_psd_foss.bigendianbitconverter import BigEndianBitConverter

步骤 3:读取资源的原始字节

PsdImage.parsed_resources 返回更低层的 UnknownResource 对象,每个对象通过 data 暴露原始负载:

image = PsdImage.load("input.psd")

for resource in image.parsed_resources:
    raw = resource.data

步骤 4:解码 32 位大端值

data = bytes([0x00, 0x00, 0x04, 0x10])  # example 4-byte big-endian field
value = BigEndianBitConverter.to_int32(data, 0)
print(f"Decoded value: {value}")  # 1040

to_int32(byte_array, offset) 从 offset 开始读取 4 字节,并按最高有效字节优先的顺序合并它们。

常见问题及解决方案

IndexError 调用时 to_int32. 字节数组必须在起始位置至少有 4 个可用字节 offset — 检查 len(byte_array) >= offset + 4 在调用之前。

值看起来字节顺序被交换了。 确认你在自己的代码其他地方没有意外使用小端序转换——PSD 资源和头字段始终使用大端序,这正是 BigEndianBitConverter 所假设的。

常见问答

BigEndianBitConverter 支持其他整数大小吗?

在此 FOSS 构建中,BigEndianBitConverter 仅提供 to_int32 —— 对于 16 位或 64 位大端值,请使用 Python 的内置 int.from_bytes(data, byteorder="big") 手动解码字节。

我在普通文档编辑时需要它吗?

不 — BigEndianBitConverter 是一个低层实用工具,用于处理您自行获取的原始字节(例如,来自未识别的图像资源)。典型的加载、编辑和保存(参见 使用 Core API).

另请参阅

 中文