Python int與byte類型相互轉化

根據Python自定義的功能,使用to_bytes函數轉化int類型數據爲byte型,然後使用from_bytes將byte類型數據轉化爲int型。
def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    int.to_bytes(length, byteorder, *, signed=False) -> bytes
    
    Return an array of bytes representing an integer.
    
    The integer is represented using length bytes.  An OverflowError is
    raised if the integer is not representable with the given number of
    bytes.
    
    The byteorder argument determines the byte order used to represent the
    integer.  If byteorder is 'big', the most significant byte is at the
    beginning of the byte array.  If byteorder is 'little', the most
    significant byte is at the end of the byte array.  To request the native
    byte order of the host system, use `sys.byteorder' as the byte order value.
    
    The signed keyword-only argument determines whether two's complement is
    used to represent the integer.  If signed is False and a negative integer
    is given, an OverflowError is raised.
    """
    pass
def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """
    int.from_bytes(bytes, byteorder, *, signed=False) -> int
    
    Return the integer represented by the given array of bytes.
    
    The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
    
    The byteorder argument determines the byte order used to represent the
    integer.  If byteorder is 'big', the most significant byte is at the
    beginning of the byte array.  If byteorder is 'little', the most
    significant byte is at the end of the byte array.  To request the native
    byte order of the host system, use `sys.byteorder' as the byte order value.
    
    The signed keyword-only argument indicates whether two's complement is
    used to represent the integer.
    """
    pass

如下舉例:

data = 100
data_byte = data.to_bytes(4, byteorder='little', signed=True)
print(type(data_byte), data_byte)
data_int = int.from_bytes(data_byte, byteorder='little', signed=True)
print(type(data_int), data_int)

輸出結果:

<class 'bytes'> b'd\x00\x00\x00'
<class 'int'> 100

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章