python代码在一个字节内设置3位,用于多种用途

2024-09-30 18:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

晚上

我正在尝试为las v1.3 specification编写一些python代码

为了提高效率,规范共享一个字节,用于4种不同的用途,如下所示:

  • 返回数字3位(位0、1、2)
  • 返回数3位(位3、4、5)
  • 扫描方向标志1位(位6)
  • 飞行线边缘1位(位7)

设置单个位是简单的部分。更难的部分是如何设置“返回数”的3位,即0到5之间的值。我可以写一些像这样狡猾的代码。。。你知道吗

def setBitsFor_numberreturns(self, int_type, numberreturns):
    if numberreturns == 0:
        return int_type
    if numberreturns == 1:
        int_type = self.bitSet(int_type, 3)
        return int_type
    if numberreturns == 2:
        int_type = self.bitSet(int_type, 4)
        return int_type
    if numberreturns == 3:
        int_type = self.bitSet(int_type, 3)
        int_type = self.bitSet(int_type, 4)
        return int_type
    if numberreturns == 4:
        int_type = self.bitSet(int_type, 5)
        return int_type
    if numberreturns == 5:
        int_type = self.bitSet(int_type, 3)
        int_type = self.bitSet(int_type, 5)
        return int_type
    return int_type
def bitSet(self, v, offset):
    '''
    Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.
    '''
    mask = 1 << offset   # Compute mask, an integer with just bit 'index' set.
    v |= mask         
    return v

但这似乎不是Python。 所以我的问题是。。。 有没有一个pythonic的方法来表示一个值(比如说0-5在一个字节内的一个特定的、非常规的位置上)?你知道吗


Tags: the代码selfindexreturnif字节def