使用 for 循环将十六进制代码排序到列中

Sort hexadecimal code into columns with for loop

我有一个排序的十六进制代码,表示为“id_type”变量。我想把它分成三列,第三列的长度取决于第二列的解码值。这是我想要的示例结果。

0001 0005 0701f83fe4
0002 0005 0000921912
0002 0005 0000921912
0004 0004 00a1d033
0005 0004 00252e28
0010 0002 0117

这是我的代码

id_type = "000100050701f83fe40002000500009219120003000400014cc80004000400a1d0330005000400252e280010000201170012000e484c543530305f56333034373042001300143839363630333230323030303237383737363446001400011f0015000e01030200030004000501060007000016000202cb300900249906000232339907000131990800073030303839363399090005323033303090110001013010000601000201060130120004000000003013000900016200ec0040010030140005fdffff5f0b30150002000d3016000200213017000104301800020004301900020061301a0008017d0196012801d4901000010160c00002038860d000012862f000020000605000017f64900001006010000100500100010050020001015003000100500400010050050002000050060002155450070002155450080001005009000100500a000100500b000100500c000100500d000146500e000400000000500f00010050100004000000005011000400000000501200040000000050130004000000005014000400000000501500040000000050160004000007d45017000200295019000400000000501a0006020000000000501b000100501c0002003c501d0006000000000000a0e7"

def hex_to_dex(id_type):
    return int(id_type, 16)

n = 4

for i in id_type:
    i = 0
    id = id_type[i:i + n]
    lendata = id_type[i + n:i + n + n]
    lendatah2d = hex_to_dex(lendata)
    data = id_type[i + n + n:i + n + n + lendatah2d * 2]
    p = len(id + lendata + data)

print(id, lendata, data)

但是当我的代码运行时,它只打印出 1 行我想要的结果。

0001 0005 0701f83fe4

如何编辑我的代码? 请帮助我。

首先,print 应该在循环内,打印每次迭代,而不是最后一次

for i in id_type:
    i = 0
    ...
    print(id, lendata, data)

然后

  • i 不应由任何循环生成,因为它不会以固定数量递增(取决于数据长度)
  • 每次读取数据时增加i
id_type = "000100050701f83fe40002000500009219120003000400014cc80004000400a1d033" \
          "0005000400252e280010000201170012000e484c543530305f563330343730420013" \
          "00143839363630333230323030303237383737363446001400011f0015000e010302" \
          "00030004000501060007000016000202cb3009002499060002323399070001319908"

def hex_to_dex(id_type):
    return int(id_type, 16)

n = 4
i = 0
while i < len(id_type) - 8:
    key = id_type[i:i + n]
    i += n
    lendata = id_type[i:i + n]
    lendatah2d = hex_to_dex(lendata)
    i += n
    data = id_type[i:i + lendatah2d * 2]
    i += lendatah2d * 2

    print(key, lendata, data)

为了避免递增索引带来的麻烦,您可以使用 io.StringIO class.

模拟从文件读取
import io

id_type = ('000100050701f83fe4'
           '000200050000921912'
           '0003000400014cc8'
           '0004000400a1d033')

stream = io.StringIO(id_type)

while True:
    row_id = stream.read(4)

    if not row_id:
        # end of "file" reached
        break

    row_len = stream.read(4)
    row_data = stream.read(2 * int(row_len, 16))

    print(row_id, row_len, row_data)