Skip to content

Instantly share code, notes, and snippets.

@clamytoe
Last active August 29, 2015 14:26
Show Gist options
  • Save clamytoe/3600f620d59742838f51 to your computer and use it in GitHub Desktop.
Save clamytoe/3600f620d59742838f51 to your computer and use it in GitHub Desktop.
Little utility that I cooked up to convert numbers between binary, hex, and decimal. It also converts MAC address > to binary > to decimal.
__author__ = 'muribe'
"""
Little utility that I cooked up to convert numbers between binary, hex, and decimal.
If a MAC address in the following format is entered:
00-11-8a-2d-ff-ff
It returns the following binary:
0000 0000 0001 0001 1000 1010 0010 1101 1111 1111 1111 1111
If that binary is put back in, it is converted to the following decimal:
0 17 138 45 255 255
To convert a decimal into either its hex or binary representation, just put that number in.
To convert a hex into either its binary or decimal representation, just prefix it with 0x:
ie 0xff.
To convert a binary number into either its hex or decimal representation, just prefix it with 0b:
ie 0b01001101 or 0b10
Shout out to all of my network buds out there!
"""
def hex_to_dec(num):
return int(num, 16)
def hex_to_bin(num):
return str(bin(int(num, 16))[2:]).rjust(8, '0')
def bin_to_hex(num):
return hex(int(num, 2))[2:].upper()
def bin_to_dec(num):
return int(num, 2)
def dec_to_hex(num):
return hex(int(num))[2:].upper()
def dec_to_bin(num):
return str(bin(int(num))[2:]).rjust(8, '0')
def main():
while True:
num = raw_input("Enter a number: ")
if num == '' or num == 'quit':
break
else:
try:
if '0x' in num:
print "Decimal:", hex_to_dec(num)
print " Binary:", hex_to_bin(num)
elif '0b' in num:
print " Decimal:", bin_to_dec(num)
print "Hexadecimal:", bin_to_hex(num)
elif '-' in num:
bin_number = ''
address = ''
bits = num.split('-')
for bit in bits:
bin_number += hex_to_bin('0x'+bit)
for digit in range(len(bin_number)):
if digit > 0 and digit % 4 == 0:
address += ' '
address += bin_number[digit]
print address
elif ' ' in num:
dec_number = list()
bits = num.split(' ')
for bit in range(0, len(bits), 2):
bit_number = bits[bit] + bits[bit+1]
dec_number.append(str(bin_to_dec('0b'+bit_number)))
print ' '.join(dec_number)
else:
print " Binary:", dec_to_bin(num)
print "Hexadecimal:", dec_to_hex(num)
except Exception, e:
print "Error:", e
exit()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment