【问题标题】:sum of bytes with sum()sum() 的字节总和
【发布时间】:2021-12-05 17:48:55
【问题描述】:

为什么下面的代码会导致TypeError

a = b'\x01'
b = b'\x02'
_tuple = (a, b)
sum(_tuple)

TypeError: unsupported operand type(s) for +: 'int' and 'bytes'

虽然 a 和 b 都是字节(使用 type(a) 快速检查

【问题讨论】:

  • 你需要定义一个初始值,或者只做 sum(*_tuple)
  • sum(_tuple, start=b'\0')
  • 在内部,sum() 将总和初始化为整数 0。然后当它尝试添加字节值时会出现类型错误。
  • @Barmar 不起作用(至少在 3.9 中),因为它会引发 TypeError
  • 你想得到什么结果?

标签: python byte


【解决方案1】:

就像sum(_tuple, b'\0') 的错误所说:

您需要改用b''.join(_tuple)

错误信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum bytes [use b''.join(seq) instead]

编辑:
允许进行实际请求的计算。

辅助函数:

def split_int(num, split):
    """convert base-10 int to other bases and return digits in a list"""
    res = []
    exp = 1
    while exp < num:
        trunc = exp
        exp *= split
        current_num = num % exp // trunc
        res.insert(0, current_num)
    return res

首先你需要将字节转换为int:

def sum_bytes(*bytes):
    """sum bytes"""
    int_list = [int.from_bytes(byte, 'big') for byte in bytes]
    # use 'little' if the smallest byte comes first.

那么你需要对整数求和:

    int_sum = sum(int_list)

最后,您需要将它们重新转换为字节。结果是 > 256 你需要上面的辅助函数:

    byte_sum = bytes(split_int(int_sum, 256))
    return byte_sum

更压缩的代码是:

def split_int(num, split):
    """convert base-10 int to other bases and return digits in a list"""
    res = []
    exp = 1
    while exp < num:
        trunc = exp
        exp *= split
        current_num = num % exp // trunc
        res.insert(0, current_num)
    return res

def sum_bytes(*bytes):
    """sum bytes"""
    int_sum = sum((int.from_bytes(byte, 'big') for byte in bytes))
    return bytes(split_int(int_sum, 256))

【讨论】:

  • +1,我认为您的反对意见不值得,但是,我认为 OP 还没有提供足够的信息来让这个答案被认为是足够的。目前尚不清楚 OP 的预期结果是什么。
  • 他可能想得到b'\x03'
  • @Barmar 我对此进行了研究并最终提供了代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 2014-08-07
  • 2018-05-21
  • 2014-04-03
  • 1970-01-01
相关资源
最近更新 更多