Last active
November 4, 2021 09:27
-
-
Save f-steff/4b61a98aa74791c3f5ab7c74b40d4191 to your computer and use it in GitHub Desktop.
Python binary manipulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def swap_bytes(byte_string): | |
""" | |
Swaps every second byte in an string. If string is uneven, the last byte is untouched. | |
1 2 3 4 becomes 2 1 4 3 | |
1 2 3 4 5 becomes 2 1 4 3 5 | |
""" | |
return b"".join([(byte_string[i:i + 2])[::-1] for i in range(0, len(byte_string), 2)]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def twos_comp(val, bits=16): | |
"""compute the 2's complement of int value """ | |
if bits == 0: # Use as many bits needed for the value. | |
bits = val.bit_length() | |
return ((val & (2 ** bits) - 1) - (2 ** bits)) * -1 # 2's compliment | |
value = 6752 | |
print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}') # 06752 = 0x1a60 = 0b0001101001100000 | |
value = twos_comp(value) | |
print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}') # 01440 = 0x05a0 = 0b0000010110100000 | |
value = twos_comp(value) | |
print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}') # 06752 = 0x1a60 = 0b0001101001100000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment