Electronic – arduino – Converting 32 bit 2’s complement to decimal number

arduinobinarymicrocontrolleruart

I have data coming from a V9261F energy measuring chip (link to datasheet), that sends it data through a UART to my Arduino microcontroller. When I read register 0x0119, I read the active power measured by the chip. But the problem is that this feedback is in 32 bits 2's complement and I can not decode it.

UART communication

Starting from the 4th byte in the stream are the data bytes in which the measured variables are stored (see data sheet pg 56 – 57). For reading register 0x0119, this should be in databyte 10 – 11 – 12 and 13 (D1) respectively 0x55, 0xE7, 0x0E and for databyte 13 0x00.

So the feedback for the active power all the bytes combined I have is 0x000EE755 -> subtract 1 (for 1 complement) = 0x000EE754 -> invert it to become decimal number = 0xFFF118AB (4293990571 dec).
But this insane big number should only represent an active power of 6.2 Watts.

What do I do wrong with converting from the 2's complement to decimal? How should this represent 6.2 watt?

Best Answer

I think you have a misunderstanding of what "2's complement" means. A positive 2's complement number is identical to a positive binary number (the most significant bit must be zero). So for 8 bits we have 0x00 (zero) to 0x7F (127). Numbers less than zero go from 0xFF (-1) to 0x80 (-128). To make a negative number positive so you can display it as a minus sign in front of a positive number you can calculate the 2's complement as you show above. Note the special case of 0x80.

So with 0x000EE754 you have a positive number of decimal 976724. There is a scaling factor between that and 6.2 of 6.3478E-6.

Probably what you want to do is to convert the number into a floating point number and do the calculations in floating point. It's already in 32-bit signed integer format.