A program I am trying to improve has the following code to add 1 to a 16-byte number in a byterray:
for k in range(15, -1, -1):
payload[k] = (payload[k] + 1) & 0x0ff
if payload[k]:
break
So, it adds 1 to the last byte, handling overflow, and if the result is falseish (0x00), it proceeds and adds 1 to the byte before it, and otherwise it stops.
This seems like a kludge to me, and I'm trying to come up with something better, if not for performance or reliability, then at least for how it looks.
So far, I've got this, which yields the same results in my tests:
hi,lo = struct.unpack('>QQ', payload)
payload = struct.pack('>QQ', hi, lo + 1)
I know that my code will fail after running at most 2^64 times, but I'm quite sure the code won't have to run more than a few hundred times for a single number, so the chance of anything more than the last couple of bytes changing is small.
Any suggestions about my intended improvement, of other/better ways to get the same result? Of course, if there is an easy fix for the 2^64 limitation, I'd love to see it!
Thank you.
2^64hahalo:struct.pack('>QQ', hi + (lo == (2**64) - 1), lo + (lo < (2**64) - 1)). Not that you need to use that at all, not withint.from_bytes()andint.to_bytes().