def convertMaskAndTrimBytesToBitString()

in python/awsgs.py [0:0]


def convertMaskAndTrimBytesToBitString(data, mask, rightShift, length):

    #   Performs multiple operations:
    #   1. Convert bytes to a Python integer bit string
    #   2. Mask values not needed
    #       e.g. 0b11111100 masked with 0b00001111 becomes 0b00001100
    #   3. Shift values we need to the right
    #       e.g. 0b00001100 shifted by 2 becomes 0b00000011
    #   4. Right-Trim the bit string to the desired length

    # Network / Big Endian format
    _BYTE_ORDER = r'big'

    try:
        #   1. Convert to int
        bytes = int.from_bytes(data, _BYTE_ORDER)
        #   2. Mask + 3 right-shift
        output = (bytes & mask) >> rightShift

        #   4. Right-Trim to the required length
        fmt = '0' + str(length) + 'b' # e.g. 04b / 08b
        output = format(output, fmt)

        return output

    except Exception as e:
        print(" (ERR) convertMaskAndTrimBytesToBitString error: %s" % e )
        return None