I have this string of hex bytes, separated by spaces:
byteString = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F"
How to add bytes in this way:
01 + 01 + 50 + 01 + 00 + 48 + 65 + 6C + 6C + 6F = 247
I have this string of hex bytes, separated by spaces:
byteString = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F"
How to add bytes in this way:
01 + 01 + 50 + 01 + 00 + 48 + 65 + 6C + 6C + 6F = 247
Considering that you have the hex sequence as a str (bytes), what you need to do is:
>>> byte_string = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F" >>> >>> l = [int(i, 16) for i in byte_string.split(" ")] # Split and conversion to int done in one step >>> l [126, 0, 10, 1, 1, 80, 1, 0, 72, 101, 108, 108, 111] >>> >>> [hex(i) for i in l] # The hex representation of each element (for checking only) ['0x7e', '0x0', '0xa', '0x1', '0x1', '0x50', '0x1', '0x0', '0x48', '0x65', '0x6c', '0x6c', '0x6f'] >>> >>> s = sum(l[3:]) >>> >>> s 583 >>> hex(s) '0x247'
You need to tackle this in 2 parts - convert the string to a list of numbers, then sum the list. For this you can use the built-in bytearray.fromhex and sum functions:
byteString = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F"
numberList = bytearray.fromhex(byteString)
total = sum(numberList)