pythonbyte转int_Python int与byte类型相互转化

根据Python自定义的功能,使用to_bytes函数转化int类型数据为byte型,然后使用from_bytesa将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

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值