Offensive PythonBinary and HexadecimalBitwise Operators with f-strings and format()
Offensive PythonBinary and HexadecimalBitwise Operators with f-strings and format()
Binary and Hexadecimal

Bitwise Operators with f-strings and format()

     Since Python 3.6, we can use f-strings to evaluate expressions inside string literals and easily print out the results. This works great for printing Bitwise Operations. If we prefer, we can also use the older method of using the format function. Below are some examples of how this can be done.
 
Example code:

bin_1 = 0b11101011
bin_2 = 0b10001111

print(f”{bin_1:08b}”)
print(f”{bin_2:08b}”)
print(“——–“)

print(f”{(bin_1 & bin_2):08b} is the AND result using an f-string.”)
print(format(bin_1 & bin_2, “08b”), “is the AND result using the format function.\n”)

print(f”{(bin_1 | bin_2):08b} is the OR result using an f-string.”)
print(format(bin_1 | bin_2, “08b”), “is the OR result using the format function.\n”)

print(f”{(bin_1 ^ bin_2):08b} is the XOR result using an f-string.”)
print(format(bin_1 ^ bin_2, “08b”), “is the XOR result using the format function.\n”)

# Notice that 10 bits are printed; the mask of 08b prints 8 bits at a minimum with leading zeros
print(f”{(bin_1 << 2):08b} is the SHIFT LEFT 2 bits result for bin_1 using an f-string.”)
print(format(bin_1 << 2, “08b”), “is the SHIFT LEFT 2 bits result for bin_1 using the format function.\n”)

print(f”{(bin_2 >> 2):08b} is the SHIFT RIGHT 2 bits result for bin_2 using an f-string.”)
print(format(bin_2 >> 2, “08b”), “is the SHIFT RIGHT 2 bits result for bin_2 using the format function.\n”)

print(f”{~bin_1:08b} is the 2’s COMPLIMENT result of bin_1 using an f-string.”)
print(format(~bin_1, “08b”), “is the 2’s COMPLIMENT result of bin_1 using the format function.”)

Output:

11101011
10001111
——–
10001011 is the AND result using an f-string.
10001011 is the AND result using the format function.

11101111 is the OR result using an f-string.
11101111 is the OR result using the format function.

01100100 is the XOR result using an f-string.
01100100 is the XOR result using the format function.

1110101100 is the SHIFT LEFT 2 bits result for bin_1 using an f-string.
1110101100 is the SHIFT LEFT 2 bits result for bin_1 using the format function.

00100011 is the SHIFT RIGHT 2 bits result for bin_2 using an f-string.
00100011 is the SHIFT RIGHT 2 bits result for bin_2 using the format function.

-11101100 is the 2’s COMPLIMENT result of bin_1 using an f-string.
-11101100 is the 2’s COMPLIMENT result of bin_1 using the format function.

Leave a Reply

Your email address will not be published. Required fields are marked *