1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python int转换为byte_Python int与byte类型相互转化

python int转换为byte_Python int与byte类型相互转化

时间:2020-12-17 16:53:38

相关推荐

python int转换为byte_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)

输出结果:

b'd\x00\x00\x00' 100

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。