Math problem

Hello,

I have an energy meter which stores the energy index in 4 registers modulo 10000 per register.
I am reading them with modbus protocol. i want the reading to be in kw thats why i divide by 1000.

So first time i tried like this.

unsigned long c_activ = node.getResponseBuffer(3) * 1000000 + node.getResponseBuffer(2) * 100000 + node.getResponseBuffer(1) * 10 + node.getResponseBuffer(0) / 1000;

.. and the reading was wrong. (if i remeber corectly sometimes was correct but most times was wrong).

Then i tried like this.

unsigned long n3 = 1000000;
unsigned long n2 = 100000;
unsigned long n1 = 10;
unsigned long n0 = 1000;

unsigned long c_activ = node.getResponseBuffer(3) * n3 + node.getResponseBuffer(2) * n2 + node.getResponseBuffer(1) * n1 + node.getResponseBuffer(0) / n0;

.. and the readings was always correct, and i only changed the numbers with variables that contains the same numbers.

Can anyone think of a reason why it dosnt work directly with numbers?
I want to get rid of the variables to save memory.. Thank you.

Can anyone think of a reason why it dosnt work directly with numbers?

Use something like:-

unsigned long c_activ = node.getResponseBuffer(3) * 1000000UL + node.getResponseBuffer(2) .....

Adding UL to a constant in a mixed arithmetic expression tells the compiler to use an unsigned long for the constant.