It originated from a small perl script used to convert hexadecimal numbers in "understanding computer principles in depth", so I wrote a Python code to implement conversion between hexadecimal and decimal numbers.
The main things used are:
1. int (x [, base])-> integer # This is a builtin class.
Convert a string or number to an integer, if possible.
For example, int ("0x11", 16) can convert the hexadecimal "0x11" into a decimal number, such as int ("100011 ″, 2) The number of binary values that can be converted is a decimal integer.
2. hex (number)-> string # convert an integer into a hexadecimal string
Return the hexadecimal representation of an integer or long integer.
3. sys. argv
The list of command line arguments passed to a Python script.
For I in sys. argv [1:], all command line parameters can be traversed (except the name of the running script ).
The Code is as follows:
#!/usr/bin/python3'''Created on Apr 5, 2012 @author: Jay Ren@module: hex_dec@note: Translation between hexadecimal and decimal numbers on the commandline arguments.'''importsysimportredef hex_to_dec(hex_num): print("{} = {}".format(hex_num, int(hex_num, 16)))def dec_to_hex(dec_num): print("{} = {}".format(hex(int(dec_num, 10)), dec_num))if __name__ == '__main__': for i insys.argv[1:]: ifre.match('^0x.*', i): hex_to_dec(i)else: dec_to_hex(i)
The execution result is as follows:
View Code BASH123456
master@jay-intel:~/workspace/py2012_Q2/src$ ./hex_dec.py 134 0x123 454433 0xffffffff0x86 = 1340x123 = 2910x1c6 = 4540x1b1 = 4330xffffffff = 4294967295
The left side of the equal sign is a hexadecimal value, and the right side is a corresponding decimal value.