Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

byte reverse AB CD to CD AB with python

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.

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.

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

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()

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Python 3.4 you can use this:

>>> data = b'xADxDExDExC0'
>>> swap_data = bytearray(data)
>>> swap_data.reverse()

the result is

bytearray(b'xc0xdexdexad')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...