Having trouble converting Excel formula to C++

I have a functional formula in Excel which I am trying to replicate in C++ for my project. For a little context, these are individual wheel speeds read via CAN in my BMW car project.

The captured data from the CAN bus is as per the below example. It consists of 8 bytes containing hex values where two bytes are used for each wheel.

unsigned char buf[8];

An example of a payload would be:

87	22	7F	2	81	2	80	2

The formula which is working as expected in Excel is shown below and in text for the first wheel:

(HEX2DEC(B2)+HEX2DEC(RIGHT(C2,1))*256)/16

I've tried many permutations in my C++ code but just can't get the correct calculation :frowning: Any help greatly appreciated !!

My non-working code is here: BMW_E46_Gauge_Cluster_Control/functions_read.cpp at main · david-morton/BMW_E46_Gauge_Cluster_Control · GitHub

the formula in your code is different from the one in your post
(HEX2DEC(B0)+HEX2DEC(RIGHT(B1,1))*256)/16
which is correct?
what should be the result from

87	22	7F	2	81	2	80	2
            // (HEX2DEC(B0)+HEX2DEC(RIGHT(B1,1))*256)/16
            wheelSpeedFl = (buf[0] + (buf[1] >> 4) * 256) / 16;
            wheelSpeedFr = (buf[2] + (buf[3] >> 4) * 256) / 16;
            wheelSpeedRl = (buf[4] + (buf[5] >> 4) * 256) / 16;
            wheelSpeedRr = (buf[6] + (buf[7] >> 4) * 256) / 16;

You are dropping the rightmost digit instead if extracting it.
You are also using integer division which gives integer results.

            wheelSpeedFl = (buf[0] + (buf[1] & 15) * 256) / 16.0;
            wheelSpeedFr = (buf[2] + (buf[3] & 15) * 256) / 16.0;
            wheelSpeedRl = (buf[4] + (buf[5] & 15) * 256) / 16.0;
            wheelSpeedRr = (buf[6] + (buf[7] & 15) * 256) / 16.0;

Why are you multiplying by 256 then dividing by 16 immediately? Waste of processor cycles.

The image from Excel shows what the expected result is, the payload being in yellow and the results in green with the formula below showing how it was achieved. The column headings B0, B1 etc are the bytes of the payload.

Many thanks for the tip I shall investigate this angle and your supplied changes. To clarify, I do want integer / float results (km/h) and that's what the Excel results are in (green cells).

Yes, will get it functional first then optimise things.

I went away and read up on the bitwise & operator and makes sense now the changes proposed by @oqibidipo !! Tested and at least stationary the results look good :slight_smile:

Will validate after work today with a proper drive !!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.