Python實現十六進位與十進位的轉換

來源:互聯網
上載者:User

起源於看到《深入理解電腦原理》裡面的用於轉化16進位數的一小段perl指令碼,於是我就寫了一個Python來實現十六進位與十進位之間的轉換。
主要用到的東西有:
1. int(x[, base]) -> integer #這是一個builtin的類
Convert a string or number to an integer, if possible.
如:int(“0×11″, 16)就可以將十六進位的”0×11″轉化為10進位的數字,再如int(“100011″, 2)可以轉化二進位的數為十進位整數。
2. hex(number) -> 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:] 即可遍曆所有的命令列參數(除啟動並執行指令碼名之外)。

代碼如下:

#!/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)

執行效果如下:

View Code BASH
123456
master@jay-intel:~/workspace/py2012_Q2/src$ ./hex_dec.py 134 0x123 454433 0xffffffff0x86 = 1340x123 = 2910x1c6 = 4540x1b1 = 4330xffffffff = 4294967295

其中等號左邊是十六進位的數值,等號右邊是對應的十進位數值。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.