Python converts hexadecimal to decimal.

Source: Internet
Author: User
Tags perl script

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 BASH
123456
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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.