2

I used the search function without success.

This I the code I want to translate to python3 code.

From my pv inverter I receive the 3 byte data.

The following c program is used to convert the data into a c float value. This code works correct. I have verified that the output is correct.

    // filename: test.c

    #include <stdio.h>
    
    // example data byte
    // byte 24 = 194
    // byte 25 = 112
    // byte 26 = 134
    // result is 
      
    int main(void)
    {   
            int iacpower = ((134 << 8 | 194) << 8 | 112) << 7 ;
            // other example int iacpower = ((135 << 8 | 230) << 8 | 165) << 7 ;

            float facpower = *((float*)&iacpower);  //convert to float

            printf("iacpower = %d\n", iacpower);
            printf("facpower = %.2f\n", facpower);
            return 0;
    } 
$ gcc -o test test.c
$ ./test
iacpower = 1130444800
facpower = 225.22

What I'm asking vor is how to convert the three byte to float using python.

I tried to unpack the data like the following python lines:

    facpower = struct.unpack('f', in_data[24,27])

and also

    iacpower = ((in_data[26] << 8 | in_data[24]) << 8 | in_data[25]) << 7
    facpower = struct.unpack('f', iacpower)

Any suggest please?

Thank you!

1 Answer 1

2

After you've computed iacpower you need to repack it, that is, pack int to bytes and unpack as a float:

>>> iacpower = 1130444800
>>> facpower, = struct.unpack('f', struct.pack('I', iacpower))
>>> facpower
225.21875
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.