Offensive PythonBinary and HexadecimalBinary and Hexadecimal Number Assignments
Offensive PythonBinary and HexadecimalBinary and Hexadecimal Number Assignments
Binary and Hexadecimal

Binary and Hexadecimal Number Assignments

     Sometimes we need to work with binary and/or hexadecimal numbers in Python. Maybe we are designing a program that is processing packet capture data, or we are working with IP addressing at a low level, whatever the case may be. In Python, we can easily assign binary and/or hexadecimal numbers to variables in a couple of different ways.

  1. Precede a binary number with 0b. Precede a hexadecimal number with 0x.
  2. Use the int function, where the first positional argument is a string representation of our binary or hexadecimal number, and the second argument is an integer representing the base value, 2 for binary, and 16 for hexadecimal.

Example code:

bin_1 = 0b1011
bin_2 = int(“1001”, 2)
hex_1 = 0x0B
hex_2 = int(“0009”, 16)

print(bin_1, bin_2, hex_1, hex_2)

Output:

11 9 11 9

     Regardless of the fact that we assigned binary and hexadecimal numbers to the variables, decimal values are printed. If we need to print the binary or hexadecimal numbers, we have to use the bin and/or hex functions for casting.

Example code:

print(bin(bin_1), bin(bin_2))
print(hex(hex_1), hex(hex_2))

Output: 

0b1011 0b1001 
0xb 0x9

And of course, it works this way as well:

print(hex(bin_1), hex(bin_2))
print(bin(hex_1), bin(hex_2))

Output: 

0b1011 0b1001 
0xb 0x9

Leave a Reply

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