如何在python

时间:2015-07-22 12:48:02

标签: python

我有intel hex文件的记忆

1879048192: 4,
1879048193: 3,
1879048194: 2,
1879048195: 1,
1879048196: 4,
1879048197: 3,
1879048198: 2,
1879048199: 1,
1879048200: 4,
1879048201: 3,
1879048202: 2,
1879048203: 1,
1879048204: 4,
1879048205: 3,
1879048206: 2,
1879048207: 1,

我想要

1879048192: 1234(with swapping),
1879048196 :1234
1879048200 :1234
1879048204 :1234
1879048208 :1234

我用

for x in range (0,count):
    for i in range(0,4):
        realdata = mapFile.values()[x:x+4]
        realdata[x+3],realdata[x+2],realdata[x+1],realdata[x+0] =                realdata[x+0],realdata[x+1],realdata[x+2],realdata[x+3]

        s = ''.join(map(str, realdata))

        realadr = mapFile.keys()[x] + offset

        offset = offset + 4

        _buf = {realadr : int(s)}

但我无法成功,我是python的新手。请建议我更好的实施。

2 个答案:

答案 0 :(得分:0)

_buf = {realaddr : int(s)}

使_buf成为具有单个条目的字典,即realaddr:int(s)的最后一个值。那不是你想要的。将其移到外面并添加合并值的逻辑:

_buf = {}
for x in range (0,count):
    for i in range(0,4):
        realdata = mapFile.values()[x:x+4]
        realdata[x+3],realdata[x+2],realdata[x+1],realdata[x+0] =                realdata[x+0],realdata[x+1],realdata[x+2],realdata[x+3]

        s = ''.join(map(str, realdata))

        realadr = mapFile.keys()[x] + offset

        offset = offset + 4

        if realadr in _buf:
           # merge the values somehow
           s = _buf[realadr] + s

        _buf[realadr] = int(s)

print _buf

答案 1 :(得分:0)

根据需要在for循环中使用mapfile.keys()重写。我使用了一个生成器对象来强制执行第4步。你想一次处理四个字节,所以你必须每次跳过四个,然后在循环内向前看以获取mapfile [x + 3]。

您会注意到我故意在mapfile中添加了一些错误,以演示代码如何处理它们。

mapfile = {
    1879048192: 0,
    1879048193: 0,
    1879048194: 0,
    1879048195: 0,
    1879048196: 4,
    1879048197: 3,
    1879048198: 2,
    1879048199: 17,
    1879048200: 0,
    1879048201: 1,
    1879048202: 0,
    1879048203: 0,
    1879048204: 4,
    # intentionally missing byte
    1879048206: 2,
    1879048207: 1,
    1879048208: 0 # single byte cannot make up a dword
}

_buf = {}
for x in (x for x in mapfile.keys() if 0==x%4):
    try:
        s = "0x{0:02x}{1:02x}{2:02x}{3:02x}".format(mapfile[x+3],mapfile[x+2],mapfile[x+1],mapfile[x+0])
        print "offset ", x, " value ", s
        _buf[x] = int(s, 16)
    except KeyError as e:
        print "bad key ", e

print "_buf is ", _buf

输出:

offset  1879048192  value  0x00000000
offset  1879048196  value  0x11020304
offset  1879048200  value  0x00000100
bad key  1879048205
bad key  1879048211
_buf is  {1879048192: 0, 1879048200: 256, 1879048196: 285344516}