Doing a bitwise operation on bytes

后端 未结 3 1754
悲&欢浪女
悲&欢浪女 2021-01-04 02:21

I got two objects, a and b, each containing a single byte in a bytes object.

I am trying to do a bitwise operation on this to get the two m

相关标签:
3条回答
  • 2021-01-04 03:18

    A bytes sequence is an immutable sequence of integers (like a tuple of numbers). Unfortunately, bitwise operations are not defined on them—regardless of how much sense it would make to have them on a sequence of bytes.

    So you will have to go the manual route and run the operation on the bytes individually. As you only have a single byte each, it’s really simple to do so though. For the same reason you also don’t need to care about endianness, as that’s only applicable when talking about multiple bytes.

    So, you could do it like this:

    >>> a, b = b'\x12', b'\x34'
    >>> bytes([a[0] & b[0]])
    b'\x10'
    
    0 讨论(0)
  • 2021-01-04 03:18

    A more general answer

    def andbytes(abytes, bbytes):
        return bytes([a & b for a, b in zip(abytes[::-1], bbytes[::-1])][::-1])
    

    Though IMO pyhon bytes objects should aready do this....

    0 讨论(0)
  • If you have a large byte string, it will be more efficient to use

    c = (int.from_bytes(a, 'big') & int.from_bytes(b, 'big')).to_bytes(max(len(a), len(b)), 'big')
    

    thanks, @Eryk Sun

    0 讨论(0)
提交回复
热议问题