python2.7 中内置的各种进制、字符串之间的转换方法总结

各种进制数的表示方法

#二进制 
    0b100101 
#八进制 
    python2中可以以0开头    eg:070560o705
   python3 zhong 0o开头的才是8进制 eg 0o7056
#十进制
    999
#十六进制
    0xFE

 

int() 

#不带参数,只能对数字转换
a = 0xF01
b = int(a)
print type(a)  # <type 'int'>
print type(b)  # <type 'int'>
print b  # 3841

带参数,支持对字符串格式的数字进行转换
demo_decimal = '17'  # string
demo_hexadecimal = 'F6'  # string
print int(decimal)  # int val=17
print int(hexadecimal, 16)  # int val= 246

 

hex() 

hex(number) -> string  #'\x6'
Return the hexadecimal representation of an integer or long integer.
将给定的数字转换成字符串形式的16进制数字,参数可以是 任意十进制数字如:97,或者16进制数如:0xFF 或者八进制数 如:077 输出string 类型,


oct() 

oct(number) -> string # '0o6'
Return the octal representation of an integer or long integer.
用法同hex

bin()

bin(number) -> string  #
Return the binary representation of an integer or long integer.

ord()

ord(c) -> integer
Return the integer ordinal of a one-character string.
是Python中的一个库函数,用于从给定字符值中获取数字值,它接受一个字符并返回一个整数,即用于将字符转换为整数,即用于获取ASCII给定字符的
只支持一个字符,即 '\x255'

   如 ord('\xff')
    ->255 ord('A')->65
    ord('a')->97

encode() 和decode()

'A5A5A5'.decode('hex') # -> '\xa5\xa5\xa5'
'\xa5\xa5\xa5'.encode('hex') # ->'a5a5a5'

 

import binascii
 binascii.b2a_hex

   """
    Hexadecimal representation of binary data.
    
      sep
        An optional single character or byte to separate hex bytes.
      bytes_per_sep
        How many bytes between separators.  Positive values count from the
        right, negative values count from the left.
    
    The return value is a bytes object.  This function is also
    available as "hexlify()".
    
    Example:
    >>> binascii.b2a_hex(b'\xb9\x01\xef')
    b'b901ef'
    >>> binascii.hexlify(b'\xb9\x01\xef', ':')
    b'b9:01:ef'
    >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
    b'b9_01ef'
    """

binascii.a2b_hex(b'68656c6c6f20776f726c64')
# b2a_hex的相反操作,必须包含偶数个数据

  """
  Binary data of hexadecimal representation.

  hexstr must contain an even number of hex digits (upper or lower case).
  This function is also available as "unhexlify()".
"""
 

bytes
bytes.fromhex()
"""
Create a bytes object from a string of hexadecimal numbers.

Spaces between two numbers are accepted.
Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
"""

 

 

 

有机会再补充

 

posted @ 2021-12-28 11:03  Orientation  阅读(900)  评论(0编辑  收藏  举报