Code should read (lowByte + 256 * highByte) rather than (lowByte + 265 * highByte), but it's better solved as follows
def int_from_bytes(b):
if not b: # special-case 0 to avoid b[0] raising
return 0
n = b[0] & 0x7f # skip sign bit
for by in b[1:]:
n = n * 256 + by
if b[0] & 0x80: # if sign bit is set, 2's complement
bits = 8*len(b)
offset = 2**(bits-1)
return n - offset
else:
return n
def getTemperature(lowByte, highByte):
return 0.1*int_from_bytes(bytearray([highByte,lowByte]))
Code should read (lowByte + 256 * highByte) rather than (lowByte + 265 * highByte), but it's better solved as follows
def int_from_bytes(b):
if not b: # special-case 0 to avoid b[0] raising
return 0
n = b[0] & 0x7f # skip sign bit
for by in b[1:]:
n = n * 256 + by
if b[0] & 0x80: # if sign bit is set, 2's complement
bits = 8*len(b)
offset = 2**(bits-1)
return n - offset
else:
return n
def getTemperature(lowByte, highByte):
return 0.1*int_from_bytes(bytearray([highByte,lowByte]))