def asn1Length(x):
    """Return a bytearray encoding an ASN1 length field based on input length.
    
    The ASN.1 length field is itself variable-length, depending on whether
    the length can be encoded in 7 bits.  If so, the length is encoded in a
    single byte with the high bit cleared.  Otherwise, the first byte's
    high bit is set, and the remaining 7 bits encode the number of following
    bytes needed to encode the length as a big-endian integer.
    
    The function is currently limited to input lengths < 65536.
    
    This function is useful when kludging together ASN.1 data structures.
    """
    if x < 128:
        return bytearray([x])
    if x < 256:
        return bytearray([0x81,x])  
    if x < 65536:
        return bytearray([0x82, int(x//256), x % 256])  
    assert False