-3

I have an LCD display that requires that display data be sent serially.

The frame for this packet is like this.

frame=dict(
    type=0x10,
    sequence=0,
    length=46,
    line=0,
    text=b'01234567890' * 4,
    checksum=0,
    eof=0x9F
)

If I generate a list of the values in a frame, I might get this.

>>> list(frame.values())
[16, 0, 46, 0, b'01234567890012345678900123456789001234567890', 0, 159]

If I sum this list to populate the checksum, an exception is raised. I can sum the list without the bytearray and I can sum the bytes object but cannot sum it together. It seems that this would be handy to do.

What is an elegant way to address this case?

kc64
  • 23
  • 1
  • 7
  • 1
    what is the checksum algorithm? how can we help you with the current info you provided? note that most checksum algorithms give a different checksum if the data is not ordered the same way. – Jean-François Fabre Sep 29 '17 at 19:07
  • Possible duplicate of [Computing an md5 hash of a data structure](https://stackoverflow.com/questions/5417949/computing-an-md5-hash-of-a-data-structure) – Mureinik Sep 29 '17 at 19:25
  • The checksum algorithm in this case is a simple sum of bytes. It does not include the EOF. I only inferred this alogiithm in my problem statement as the question is mainly pointed at how to best sum two objects both of which are summable in some case. – kc64 Sep 29 '17 at 19:26

1 Answers1

0

I wouldn't consider it elegant, but heres a way to do it all in one line:

sum(i if type(i) in(int, float) else sum(i) for i in l)

The issue is that sum wants a list of values that can be added together. If you try to manually add a number and a byte array together, you'll get the same error.

lancew
  • 780
  • 4
  • 22
  • I like it. It's not as elegant as sum(frame) but it works. Many thanks. I'll check this answer later unless something more elegant shows up. ;-) – kc64 Sep 29 '17 at 19:41
  • Any time. Note that this line will fail if your list contains types that sum would normally fail on. – lancew Sep 29 '17 at 19:44
  • If you iterate over a bytes object, you get a sequence of ints. Seems like summing a list of ints containing also a bytes or bytearray should continuing the summing. – kc64 Sep 29 '17 at 21:17