使用Python将字节反向AB CD转换为CD AB [英] byte reverse AB CD to CD AB with python

查看:98
本文介绍了使用Python将字节反向AB CD转换为CD AB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.bin文件,我想简单地字节反转十六进制数据。比如说@ 0x10,它读取AD DE DE C0,想要读取DE DE C0 DE。

I have a .bin file, and I want to simply byte reverse the hex data. Say for instance @ 0x10 it reads AD DE DE C0, want it to read DE AD C0 DE.

我知道有一个简单的方法可以做到,但是我我是一个初学者,只是学习python,并且正在尝试制作一些简单的程序来帮助我完成日常任务。我想这样转换整个文件,而不仅仅是0x10。

I know there is a simple way to do this, but I am am beginner and just learning python and am trying to make a few simple programs to help me through my daily tasks. I would like to convert the whole file this way, not just 0x10.

我将在起始偏移量0x000000进行转换,并且块大小/长度为1000000。

I will be converting at start offset 0x000000 and blocksize/length is 1000000.

这是我的代码,也许您可​​以告诉我该怎么做。我确定我只是没有得到它,而且我是编程和python的新手。如果您能帮助我,我将非常感谢。

here is my code, maybe you can tell me what to do. i am sure i am just not getting it, and i am new to programming and python. if you could help me i would very much appreciate it.

def main():
    infile = open("file.bin", "rb")
    new_pos = int("0x000000", 16)
    chunk = int("1000000", 16)
    data = infile.read(chunk)
    reverse(data)

def reverse(data):
    output(data)

def output(data):
    with open("reversed", "wb") as outfile:
        outfile.write(data)

main()

,您可以看到用于反转的模块,我尝试了许多不同的建议,它将要么通过原始文件,要么抛出错误。我知道模块反向现在是空的,但是我已经尝试过各种方法。我只需要反向模块即可将AB CD转换为CD AB。
感谢您的任何输入

and you can see the module for reversing, i have tried many different suggestions and it will either pass the file through untouched, or it will throw errors. i know module reverse is empty now, but i have tried all kinds of things. i just need module reverse to convert AB CD to CD AB. thanks for any input

编辑:文件为16 MB,我想反转整个文件的字节顺序。

the file is 16 MB and i want to reverse the byte order of the whole file.

推荐答案

在Python 2中,二进制文件被读取为字符串,因此字符串切片应轻松处理相邻字节的交换:

In Python 2, the binary file gets read as a string, so string slicing should easily handle the swapping of adjacent bytes:

>>> original = '\xAD\xDE\xDE\xC0'
>>> ''.join([c for t in zip(original[1::2], original[::2]) for c in t])
'\xde\xad\xc0\xde'

在Python 3中,二进制文件被读取为字节。仅需进行少量修改即可构建另一个字节数组:

In Python 3, the binary file gets read as bytes. Only a small modification is need to build another array of bytes:

>>> original = b'\xAD\xDE\xDE\xC0'
>>> bytes([c for t in zip(original[1::2], original[::2]) for c in t])
b'\xde\xad\xc0\xde'

您还可以使用< > endianess 格式代码,位于结构模块以实现相同的结果:

You could also use the < and > endianess format codes in the struct module to achieve the same result:

>>> struct.pack('<2h', *struct.unpack('>2h', original))
'\xde\xad\xc0\xde'

快乐字节交换:-)

这篇关于使用Python将字节反向AB CD转换为CD AB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆