Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flip a byte in python?

I'm trying to decode a file that's a collection of reversed bytes. Currently, my code reads and copies the file, but I want to edit some of the bytes before I write out the copy. After printing the file's binary in string format, it looks like:

b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00

...and so on. I would like to flip the bytes that read out as \x** like so:

\x01 → \x10 , \x81 → \x18 , \x40 → \x04 , \xae → \xea

like image 870
Drew Avatar asked Mar 30 '17 08:03

Drew


People also ask

How do you switch bytes in Python?

byteswap() in Python. numpy. ndarray. byteswap() function toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place.

How do you reverse a byte string in Python?

Reverse the string using Python reversed() and string. join() and methods. The Python reversed() method takes a sequence and returns an iterator that accesses the given sequence in reverse order. Since a string is a sequence of characters, we can use the reversed() method to get the string characters in reverse order.

What is a byte flip?

One of the first programming puzzles I solved on my own was a byte flip. That's the process for taking a binary value and flipping it: You transpose bits 0 through 7 to bits 7 through 0. This is a puzzle that comes up frequently in programming, but one for which no single solution is preferred.


1 Answers

You want to swap the 4 first bits with the 4 last bits of the byte. Just rebuild the bytes array in a list comprehension with some shifting & masking:

>>> b = b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00'

>>> bytes(((x<<4 & 0xF0) + (x >> 4)) for x in b)
b"'\x00\x00\x00`\x00\x05\x00A\x00\x01\x00\xe0\x00\x05\x00Q\x00\x92s\x8f\x97\x82\xd3\x82\xbd\x82\xe8\x80\x00"
like image 163
Jean-François Fabre Avatar answered Sep 18 '22 12:09

Jean-François Fabre