Drew
Drew

Reputation: 63

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

Upvotes: 6

Views: 3101

Answers (2)

Rayzzor
Rayzzor

Reputation: 221

Your question needs some clarification. Are you swapping nibbles in the string representation or binary. If in binary, do you want to swap nibbles on printable characters as well (e.g. for the portion ...\x00 )7 \xf8 y(=( \xdb..., the bolded characters are not in \x?? format, so should they swap nibbles?)?

If you want the swap on a string representation and only on \x?? portions, then you could use a regular expression like this:

import re
preswap = <set to your string>
swapped = re.sub(r'(\\x)(.)(.)',r'\1\3\2',preswap)

This creates 3 sequential match elements: '\x', any single char (first), any single char (second). When this pattern is found, it is replaced with match items 1, then 3 (the second single char), then 2 (the first single char) and the result is in the swapped variable.

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140287

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"

Upvotes: 5

Related Questions