The goal is to be able to do:
struct.pack('!H', x)
But if x
is greater than 65535
then this will fail for obvious reasons.
I'm not a wizard with bit manipulation but I've understood that <<
operations will loose any shifted bits. But I have no idea how to extract one or more carrying bits from the binary/bytes string and add the carry value to the set of two bytes trailing the carrying bytes.
And I need to traverse the bytes string by 2 bytes each time and sum them up against the previous two bytes. Occasionally this will generate a value greater than 65535
- this is where I need to extract the carry bit from the result - and perform a +
operation on the result with the carry bit itself (see picture below).
This is what I'm trying to accomplish:
(In this case the carrying bit were only one, and the 2 trailing bytes would get +1
as a result.)
And this is what I've got so far:
from struct import unpack, pack
from binascii import *
even_bytes_string = b'\x45\x00\x00\x3c\x1c\x46\x40\x00\x40\x06\xac\x10\x0a\x63\xac\x10\x0a\x0c'
result = None
for i in range(0, len(even_bytes_string)-1,2):
if not result:
result = unpack('!H', even_bytes_string[i:i+2])[0]
continue
result += unpack('!H', even_bytes_string[i:i+2])[0]
if result > 65535:
# Got a carry bit.
pass
print(result)
print(pack('!H', result))
I literally have no idea how to do this quite simple task, without converting the result of a add operation into actual binary representation in string format (11001...
). And then do string manipulation s = s[-16:]+s[:-16]
(oversimplified), finally converting it back to a set of 2 bytes. It doesn't seam practical, fast or very "correct".
I'm hoping one of you know your way around bit manipulation in Python that could tell me what the proper way of doing this is. There has to be some.
A slightly more confusing picture of what I'm trying to accomplish (of keeping result at 2 bytes, cutting away any carrying bits and adding them to result as a "separate" value.):