Slicing a hexadecimal string by address range

Let's say I have a hexadecimal string:

EPC = '00000800031C1060EC9FBD3C00000000'

The specification document defines the address range for the various fields that the string represents. E.g. the range of addresses is 48h-53h (12 bits), represents the "agency" field. I know (from experience) this represents 3 pieces of “1C1” in hexadecimal EPC.

Similarly, I want to be able to decode other fields with a specified range of addresses, so my question is:

How to use the address range information in a specification to extract the pieces that it represents from hexstring, EPC? In particular, I am looking for a function of the following type:

def fun(addressrangeinhex,bits, hexstring):
    # addressrangeinhex is 48h-53h in my example above
    # hexstring is EPC string in my example above
    # bits is 12 bits in my example above
    return rangeofindexinhexstring

Thus, using the function for my example, I should get (index = 10, index = 12).

+4
2

, , . ..: '48h-53h'. , . , , .

:

def get_sub_register_value(sub_reg_bits_addr, bit_string):
    """
    Given a register address description string, and a register value
    string, return the bits from the value described by the address

    :param sub_reg_bits_addr: string of the form '48h-53h'
    :param bit_string: register value string of the form,
        '00000800031C1060EC9FBD3C00000000'
    :return: returns string of sub register: eg
    """
    start, end = (int(x[:-1], 16) for x in sub_reg_bits_addr.split('-'))
    value = int(bit_string, 16)
    mask = (1 << (end - start + 1)) - 1
    return ("%x" % ((value >> start) & mask)).upper()

:

EPC = '00000800031C1060EC9FBD3C0000000'
agency = '48h-53h'
pattern = 'FEDCBA98765432109876543210'

assert get_sub_register_value(agency, EPC) == '1C1'
assert get_sub_register_value('0h-3h', pattern) == '0'
assert get_sub_register_value('1h-4h', pattern) == '8'
assert get_sub_register_value('5h-8h', pattern) == '0'
assert get_sub_register_value('5h-9h', pattern) == '10'
assert get_sub_register_value('4h-9h', pattern) == '21'
assert get_sub_register_value('3h-9h', pattern) == '42'
+1

:

bits = '{0:0128b}'.format(int(EPC,16))
agency = int(bits[40:52],2)

print(hex(agency))  # 1C1
+2

Source: https://habr.com/ru/post/1669222/


All Articles