Reputation: 168
This python statement gives the expected value when I wrap each shift with parentheses, otherwise it gives 0 :
Coef = ((0xFF&resp[0])<<24) + ((0xFF&resp[1])<<16) + ((0xFF&resp[2])<<8) +(0xFF&resp[3])) #OK
Coef = (0xFF&resp[0])<<24 + (0xFF&resp[1])<<16 + (0xFF&resp[2])<<8 +0xFF&resp[3]) #NOK
From my point of view as a C developer, having in mind that both Coef and resp are unsigned ints this statements should be equivalent.
My guess is that Python is confused about the type of the var when the parenthesis are absent.
Upvotes: 0
Views: 103
Reputation: 224904
Nothing to do with types; +
has a higher precedence than <<
. (This is also the case in C.) Your expression is parsed as:
((0xFF & resp[0])
<< (24 + (0xFF & resp[1]))
<< (16 + (0xFF & resp[2]))
<< (8 + 0xFF & resp[3]))
Also, if resp
is a bytes
(there’s a good chance it should be), you can just:
int.from_bytes(resp[:4], 'big')
If you have to use Python 2 for some reason, struct.unpack
can do the same job:
Coef, = struct.unpack('>I', resp[:4])
Upvotes: 5