对字节进行按位运算

对字节进行按位运算

本文介绍了对字节进行按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象, a b ,每个对象在bytes对象中都包含一个字节.

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

我正在尝试对此进行按位运算,以获取两个最高有效位(big-endian,因此位于左侧).

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

但是,它生气地在我的脸上吐出了 TypeError .

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'

有什么方法可以对两个字节执行AND操作而不必考虑主机系统的字节顺序吗?

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

推荐答案

字节序列是不可变的整数序列(如数字元组).不幸的是,没有在它们上定义按位运算-无论在字节序列上使用它们有多大意义.

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.

因此,您可以这样做:

>>> a, b = b'\x12', b'\x34'
>>> bytes([a[0] & b[0]])
b'\x10'

这篇关于对字节进行按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:38