This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Two's complement format from sensor vs IQ Math Library

Other Parts Discussed in Thread: TMP102

Hello Guys, 

I have a couple of TMP102 connected over i2c to my F28027 microcontroller. Everything works well. I also use the IQ math library (a brilliant thing btw). My sensors return temperature in fractional two's complement format therefore it is practically a Q number already. I store the read-out value (from i2c) in Uint16 and my function returns _iq format.

However, the data from TMP102 are 12b only. Treating (casting) them like _iq4 (or _iq8 depending on alignment) works only for positive numbers. For negative numbers I need to check the most significant bit (bit 11) and then modify the rest of bits in 32b variable (_iq number).

Long story short I need to set bits 31:12 to 1 if the bit 11 is negative.

Now comes the question:

What is the most elegant way to do that ? 

Thanks in advance, 

Jiri

  • Hi Jiri,

    Jiri Panacek85 said:
    What is the most elegant way to do that ? 

    Cast the 12 bit value as a signed integer, left shift by 4 and then right shift by 4

    int16_t a = ((int16_t)raw << 4) >> 4)

    When you right shift a signed integer it will sign extend, i.e. the most significant bit gets shifted in. In assembly it translates to doing a logical left shift of 4 and then an arithmetic right shift of 4

  • Hi Vishal,

    thank you! I tested two different versions.

    The first one is from you:

        int32 data;
        data = (((int32) hal_I2CRead(add, reg, 2) << 16) >> 20);
        return ((_iq4)data);

    my hal_I2CRead function returns Uint32. The 12b result from a TMP102 is aligned to left. For that reason I shift 16 times to left and 20 times to right to ger _iq4.

    The second version comes from http://graphics.stanford.edu/~seander/bithacks.html#FixedSignExtend  "Sign extending from a constant bit-width" It uses the nice trick with bitfilds in C.

        struct {int32 x: 12;} data;
        data.x = (hal_I2CRead(add, reg, 2) >> 4);
        return ((_iq4)data.x);

    I also need to check what happens when optimization is enabled.

    Best Regards, Jiri