I've been trying to figure out why this byte array leads to different results using two approaches:
print(msg[16:20])
>>> b'\xe4\x86\xaaU'
msg[16:20].hex()
>>> e486aa55
print(int.from_bytes(msg[16:20], byteorder='big', signed='False'))
>>> -460936619
print(unpack_from('!I', msg, offset=16)[0])
>>> 3834030677
print(unpack('!I', msg[16:20])[0])
>>> 3834030677
How is it, that using the builtin from_bytes()
function is calculating a wrong result? I've recalculated it on my own (https://stackoverflow.com/a/50509434) and the result should be similar to the one using unpack()
228*256^3+134*256^2+170*256^1+85+256^0 = 3834030677
Hope to find my fault / wrong thinking with your guys help - thanks a lot in advance!
Use signed = False
instead of signed = 'False'
.
'False'
is a string and since it's non-empty, it is treated as a truthy value. Therefore, the number gets signed.
k = b'\xe4\x86\xaaU'
# UNSIGNED
print(int.from_bytes(k, byteorder = 'big', signed = False))
# SIGNED
print(int.from_bytes(k, byteorder = 'big', signed = True))
print(int.from_bytes(k, byteorder = 'big', signed = 'False'))