How to flip a byte in python?
I am trying to decode a file that is a set of backward bytes. Currently my code reads and copies the file, but I want to edit some of the bytes before I write out a copy. After printing a binary file in string format, it looks like this:
& r \ x00 \ x00 \ x00 \ x06 \ x00P \ x00 \ x14 \ x00 \ x10 \ x00 \ x0e \ x00P \ x00 \ x15 \ x00) 7 \ xf8y (= (\ XDB (\ x8e \ x08 \ x00
... etc. I would like to flip the bytes that count as \ x ** like this:
\ x01 β \ x10, \ x81 β \ x18, \ x40 β \ x04, \ xae β \ xea
source to share
You want to swap the first 4 bits for the last 4 bits of a byte. Just rebuild the array bytes
in a list comprehension with some modifications and 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"
source to share
Your question needs some clarification. You are replacing nibbles in string or binary. If in binary you want to also swap lumps on printable characters (e.g. for the ... \ x00 part ) 7 \ xf8 y (= ( \ xdb ..., bold characters not in \ x ?? format, so they should change pieces?)?
If you want to swap to string representation and only to \ x ?? parts, then you can 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 consecutive match elements: '\ x', any single char (first), any single char (second). When this pattern is found, it is swapped to match items 1, then 3 (second single char), then 2 (first single char), and the result is in the swapped variable.
source to share