python 如何以优雅的方式反转字节顺序?(从big-endian到little-endian)[duplicate]

u3r8eeie  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(131)
    • 此问题在此处已有答案**:

How can I convert a 256-bit big endian integer to little endian in Python?(2个答案)
Python - Decimal to Hex, Reverse byte order, Hex to Decimal(5个答案)
昨天关门了。
大家好,网友们!
这是我现在正在使用的方法,如果十六进制值变大,它就不是很优雅,也不是很有用:

"compressed_filled_01" is an hex value, 0x00024680

########## File 00 ##########

# Get the size of file 00 in bytes
file_00_size = os.path.getsize("OPENING_00.LZS")

# 0x5C + file_00_size
modified_file_00_size = 0x5C + file_00_size

# Convert the modified file size to a hexadecimal string
hex_00_converted = hex(modified_file_00_size)[2:].rstrip("L")

# Fill with zeros
filled_00 = str(hex_00_converted).zfill(8)

# Convert from big endian to little endian
little_endian_00 = filled_00[6] + filled_00[7] + filled_00[4] + filled_00[5] + filled_00[2] + filled_00[3] + filled_00[0] + filled_00[1]

# Write to the file
f.write(binascii.unhexlify(little_endian_00))
The result is the expected value, that is 0x80460200

现在,应该有一个更优雅的方法,一个我还没有找到。我到处找,甚至使用OpenIA聊天,但没有用。
可能是反向字节数组?按位运算符?
PD:顺便说一下,我使用的是Python 2.7.18。

nbysray5

nbysray51#

可以使用struct包将整数转换为big endian或little endian格式的字节数组:

import struct
file_00_size = os.path.getsize("Untitled.ipnb") # Using a file that exists on my system
# '<' is for little-endian, 'I' is for unsigned integer:
bites = struct.pack('<I', file_00_size)
print([hex(b) for b in bites])

>>> ['0x4c', '0x60', '0x0', '0x0']

您可以使用将其复制回无序整数

reversed_value = struct.unpack('>I', bites)
print(hex(reversed_value[0]))

>>> 0x4c600000
ffvjumwh

ffvjumwh2#

我的智力不是人造的。抱歉!
您的消息可能来自传统协议,该协议设计用于在为16位字设计的协议中传输32位数据。在16位到32位转换的时代(1970年到1990年),许多方案被“发明”为将32位压缩为4个字节:

  • B3 B2 B1 B 0(自然方式)
  • B2 B3 B0 B1
  • B0 B1 B2 B3
  • B1 B0 B3 B2

你可以用一个简单的循环来转换你的有效负载,如下所示:

i = 0
while i < len(payload):
  b = payload[i:i+3] # get a slice (to abbreviate)
  lw = # do some mangling (see later)
  payload[i:i+3] = lw
  i += 4

并且碾压可以是以下之一:

  • lw =(B[0],b[1],b[2],b[3])#自然方式
  • lw =(B[1],b[0],b[3],b[2])#用于小端16位字
  • lw =(B[3],b[2],b[1],b[0])
  • lw =(B[2],b[3],b[0],b[1])

仅此而已。
请注意,此答案不需要168 GPU和150 J能量。

相关问题