fsl_common.h in SDK 2.7 for LPC845BRK:
Why are the results of the formulas casted to 64 bit on a 32 bit platform?
64 bit at calculation time is mandatory to avoid overflow, of course. But the result?
Thank you for your interest in NXP Semiconductor products and for the opportunity to serve you.
Casing to uint64_t can assure eliminate the overflow accident, it can make the software more robust.
Yes, of course, as I wrote during calculation time. So there can't be an overflow. But the result of the calculation is 64 bit and redundantly casted to 64 bit again. But the platform is only 32 bit. So if making a final cast then it should be 32 bit.
(uint64_t)(((uint64_t)(us) * (clockFreqInHz)) / 1000000U)
No, that is wrong. You can assign the values to a 64-bit value. Just because the chip is 32 bit does NOT mean It can’t handle 64 bit values. The unsigned long long data type in C is 64 bit and can be used with lpc845. (The compiler will generate code that works - look at the Ggenerated code, and try it yourself)
So to summarise, this code is perfectly correct.
Well, that was not my question. Generally you can cast to whatever is supported by the chosen language, toolchain and so on. Of course.
But my point of view here is: LPC845 is a 32 bit platform. It doesn't have 64 bit registers (as far as I know). And the intended use of this macro in this SDK is to calculate a value which is loaded into a register of a timer peripheral. And this register is usually 32 bit, sometimes less (e.g. MRT or SysTick). So why casting to 64 bit? Because you can?
0. These macros are not *exclusively* for writing to registers. They are general purpose macros for manipulating timer values
1. The whole calculation is done in 64-bit. You don't need 64-bit registers to do 64-bit calculations.
2. The result *IS* is 64-bit value (whether you want to accept that or not). If you cast it to 32-bit, you will not lose precision - you will lose the UPPER part of the value - the most significant part of the value!
3. If you want to cast the value to 32-bit, you first need to make sure that you will not lose the upper part:
if (result_64_bit <= UINT32_MAX) result_32_bit = (uint32_t) result_64_bit; else error("result too large for 32 bits);
Note that when counting micro-seconds a 32-bit value overflows after 1 hour 11.5 minutes