Conversion between Python's various binaries

Source: Internet
Author: User
Tags unpack

Reprinted from: http://blog.chinaunix.net/uid-21516619-id-1824975.html

Python built-in functions after 2.6

#10进制转为2进制
>>> Bin (10)
' 0b1010 '

#2进制转为10进制
>>> Int ("1001", 2)
9

#10进制转为16进制
>>> Hex (10)
' 0xa '

#16进制到10进制
>>> int (' FF ', 16)
255

>>> int (' 0xAB ', 16)
171

#十进制转为八进制
>>print ("%o"% 10)
>>12


#16进制到2进制
>>> Bin (0xa)
' 0b1010 '

#10进制到8进制
>>> Oct (8)
' 010 '

#2进制到16进制
>>> Hex (0b1001)
' 0x9 '

#IP地址之间的转换
Import socket
Import struct
def ip2hex (IP):
Return Hex (Struct.unpack ("! I ", Socket.inet_aton (IP)) [0])

def ip2long (IP):
Return Struct.unpack ("! I ", Socket.inet_aton (IP)) [0]

def long2ip (Lint):
Return Socket.inet_ntoa (Struct.pack ("! I ", lint))


Conversion between Python's binaries (go)

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.