【问题标题】:int class constructor accepts bytes, or bytearray instance?int 类构造函数接受字节,还是 bytearray 实例?
【发布时间】:2020-10-03 03:56:13
【问题描述】:

我正在学习 Python,我对 int 类构造函数有点困惑

int 类构造函数接受字节还是字节数组实例?


来自文档: https://docs.python.org/3/library/functions.html#int

class int([x])
class int(x, base=10)

如果x 不是数字或者如果给出了基数,则x 必须是字符串、字节或字节数组实例,表示基数为基数的整数文字。


如果我传递 bytes 实例,则会收到以下错误。

i = 10
b = bytes(i)

val = int(b)

输出:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    val = int(b)
ValueError: invalid literal for int() with base 10: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

【问题讨论】:

    标签: python constructor integer


    【解决方案1】:

    指的是文本字节:

    >>> int(b'123')
    123
    

    你似乎在寻找int.from_bytes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2016-01-26
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多