-1

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
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
thomas
  • 11
  • 2
  • How is the original set of bytes stored? In a list of integers, a single string, etc? – Rhumborl Feb 29 '20 at 13:36
  • string eg: "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F B8" – thomas Feb 29 '20 at 13:37
  • Does this answer your question? [hexadecimal string to byte array in python](https://stackoverflow.com/questions/5649407/hexadecimal-string-to-byte-array-in-python) – Rhumborl Feb 29 '20 at 13:42
  • there is a conversion of hexadecimal string to byte array. There is no addition. – thomas Feb 29 '20 at 13:51
  • 1
    @thomas ***"there is a conversion"***: First you have cast, then you can add. You can't do math's with string objects. – stovfl Feb 29 '20 at 14:01

2 Answers2

0

Considering that you have the hex sequence as a str (bytes), what you need to do is:

  • Split the sequence in smaller strings each representing a byte (2 hex digits): "7E", "00", ...
  • Convert each such string to the integer value corresponding to the hex representation (the result will be a list of integers)
  • Add the desired values (ignoring the 1st 3)
>>> 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'
CristiFati
  • 38,250
  • 9
  • 50
  • 87
0

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)
Rhumborl
  • 16,349
  • 4
  • 39
  • 45