G'day all,
I have a Webasto heater in my car. It reports battery voltage in mV.
Among other things, I have an interface where an external status LED flashes stuff out on request of a remote, and I wanted to add battery voltage as one of the parameters. I figured 3 digits was enough, so I needed to divide the voltage by 100 (or thereabouts).
I don't use anything other than addition or subtraction anywhere in the code, so the challenge was to do a "near enough" divide by 100 with close enough rounding to give me +/- 100mV on the output without pulling any maths routines. The limitations are :
- Voltage is in a 16 bit register in mV, so it's never going to be high enough to hit the MSB.
- Result is in an 8 bit register because if it exceeds 160 then I have bigger things to worry about.
This is what I came up with :
- heater_voltage is the raw result from the heater (u16). Both volt and vtemp are u8.
// Hacky divide by 98.81
vtemp=heater_voltage >> 7 & 0xff; // 7
volt=vtemp;
vtemp=vtemp >> 2; // 9
volt += vtemp;
vtemp=vtemp >> 3; // 12
volt += vtemp;
vtemp=vtemp >> 1; // 13
volt += vtemp;
It does the job because precision is not a requirement. I wanted to see if I could minimise the generated code size and stay within a "yeah, that's useful".
This isn't a contest of any kind, I'm more interested to see of someone comes up with a "yeah, here's how to do it better".