Using Hex and Binary Numbers in Python

One of the first questions forensic investigators ask about when writing python programs or scripts is how do I handle Hex and Binary numbers and perform simple operations?

Python has built in intuitive capabilities to handle such numbers. Remember Python is designed to be as easy to read as English.

Opening the Python shell we can see how easy this really is.

> python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type “help”, “copyright”, “credits” or “license” for more information.

# First set the variable named value = to the decimal number 127
>>> value = 127
# displaying the number in hex as you would suspect is as easy and saying
# show me the hex representation of the variable “value”. using the proper syntax of course
>>> hex(value)
# I like to see my hex numbers in all caps, I know old school
# so I add on the upper() function as shown below
>>> hex(value).upper()

#displaying the number in binary works the same way
>>> bin(value)
# what if we want to “Exclusive Or” two hex values together?
# we first set variable A = to a hex 20 and variable B = to a hex 40
>>> A = 0x20
>>> B = 0x40
# then we use the carrot operator to create the new variable C
# (this operator represents “Exclusive Or” in most languages)
>>> C = A ^ B

# then we use the hex function once again to display the result
>>> hex(C).upper()

# and of course we then would like to display the variable C in binary
>>> bin(C)

As the saying goes “as easy as pie”
One of the earliest uses of this idiom was in a comic story found in the The Newport Mercury (a Rhode Island Newspaper) back in 1887.

This entry was posted in Example. Bookmark the permalink.

Leave a Reply

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

× nine = 36