Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

python - Doing a bitwise operation on bytes

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 most significant bits (big-endian, so to the left).

a = sock.recv(1)
b = b'xc0'
c = a & b

However, it angrily spits a TypeError in my face.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'bytes' and 'bytes'

Is there any way I can perform an AND operation on the two bytes without having to think of the host system's endianness?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...