SBAA588 April 2024 LM73 , LM75B , LM95071 , TMP100 , TMP101 , TMP102 , TMP103 , TMP104 , TMP107 , TMP1075 , TMP108 , TMP112 , TMP114 , TMP116 , TMP117 , TMP121 , TMP122 , TMP123 , TMP124 , TMP126 , TMP144 , TMP175 , TMP1826 , TMP1827 , TMP275 , TMP400 , TMP401 , TMP411 , TMP421 , TMP422 , TMP423 , TMP431 , TMP432 , TMP435 , TMP451 , TMP461 , TMP464 , TMP468 , TMP4718 , TMP75 , TMP75B , TMP75C
/* C Decode 12-bit Q4 */
unsigned char b1 = 0xff;
unsigned char b2 = 0xf0;
/* combine 8 bit bytes into 16 bit word,
apply signed type cast to upper byte */
int x = (signed char) b1 << 8 | b2;
/* shift to discard unused bits */
int y = x >> 4;
/* Q4 is 2^-4 = 1/16 = 0.0625
cannot use shift operators on float
use multiply or divide to create right shift */
float a = y * 0.0625f;
/* discard Q4 bits for a whole number result */
int b = y >> 4;
/* scale by 1000 then shift by Q# to get
fractional result without float data type */
int c = y * 1000 >> 4; /* milliCelsius */
/* a is -0.0625, b is -1, and c is -63 */
printf("x:%d y:%d a:%f b:%d c:%d\n",x,y,a,b,c);
/* C Encode 12-bit Q4 */
float in = -0.0625f;
/* Q4 is 2^-4 = 1/16 = 0.0625
cannot use shift operators on float
emulate left shift using multiply */
short int r = in * 16;
/* left shift to create unused/discard bits */
short int s = r << 4;
/* s is 0xFFF0 */
printf("r:%d s:%d sx:%hx",r,s,s);
A | B | C | D | E | |
---|---|---|---|---|---|
1 | 1810 | =HEX2DEC(A1) | =IF(B1>=2^15,B1-2^16,B1) | =INT(C1*2^-4) | =D1*0.0625 |
2 | -0.0625 | =IF(A2<0,A2+2^8,A2) | =INT(B2*2^4) | =C2*2^4 | =DEC2HEX(D2) |
A | B | C | D | E | |
---|---|---|---|---|---|
1 | 1810 | 6160 | 6160 | 385 | 24.0625 |
2 | -0.0625 | 255.9375 | 4095 | 65520 | FFF0 |
The following code shows a complete JavaScript and Python decode design for 12-bit, Q4 that can be used to read temperature data.
/* JavaScript */
function decode(x) {return (((x & 0x8000) ? x - 0x10000 : x) >> 4) * 0.0625}
let x = decode(0x1810)
let y = decode(0xFFF0)
/* x is 24.0625 and y is -0.0625 */
# Python
def decode(x): return ((x-0x10000 if (x & 0x8000) else x) >> 4) * 0.0625
x = decode(0x1810)
y = decode(0xFFF0)
# x is 24.0625
# y is -0.0625
The following code shows temperature encoding JavaScript and Python design for 12-bit Q4 that can be used to encode temperature limit or offset settings.
/* JavaScript */
function encode(x) {return ((x < 0 ? x + 0x100 : x) * 16) << 4}
let x = encode(24.0625).toString(16)
let y = encode(-0.0625).toString(16)
/* x is '1810' and y is 'fff0' */
# Python
def encode(x): return int((x+0x100 if (x < 0) else x) * 16) << 4
x = hex(encode(24.0625))
y = hex(encode(-0.0625))
# x is '0x1810'
# y is '0xfff0'