((((((44 * 256) + 33) * 256) + 22) * 256 ) + 11) = 740,365,835
This is what my calculator says. This is what Excel tells me. This is what Codeblocks and gcc report.
Arduino however,
uint32_t packed = ((((((44 * 256) + 33) * 256) + 22) * 256 ) + 11);
gives me 5643 which is 740365835 mod 2^16.
If I perform the steps one by one, no problem, it just won't handle the compound statement.
And you pull back to uint32_t packed = ((44 * 256) + 33) * 256; you get 8448 which is also mod 65536.
As it turns out, implicit casting with the Arduino/AVR compiler does NOT include the variable type of the result (L value), only those within the math so one of the discrete integers must be cast to a long for this equation to work.
So where ((((((44 * 256) + 33) * 256) + 22) * 256 ) + 11) = 5643,
((((((44 * (long)256) + 33) * 256) + 22) * 256 ) + 11) = 740365835.
Is there a switch/fuse/compiler directive to change this? GCC will implicitly cast to the type of the result variable, or am I missing something?
pert
September 16, 2017, 4:39pm
2
There's some useful information under the "U & L formatters" section of this reference page:
The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.
system
September 16, 2017, 4:39pm
3
uint32_t packed = ((((((44UL * 256) + 33) * 256) + 22) * 256 ) + 11);
unless you designate the rValue as 32 bit, your expression is evaluated to Arduino's 16bit default.
Try coercing the values into uint32_t values to accomplish what you want:
uint32_t packed = ((((((44UL * 256UL) + 33UL) * 256UL) + 22UL) * 256UL ) + 11UL);
Thanks guys, advice taken and applied. Thought maybe there was a global switch that would allow implicit casting to the type of the lValue.
DKWatson:
Thanks guys, advice taken and applied. Thought maybe there was a global switch that would allow implicit casting to the type of the lValue.
If you were on a 32bit Arduino, they would evaluate as 32bit int s
this is a very common tripping point for those new to the platform