I have this code which provides an erroneous unsigned long number.
char buff; int unsigned long bytes; bytes = 48 * 70 * 144; sprintf(buff,"%lu bytes\n", bytes); BTPort.print(buff);
OUTPUT: 20088 bytes
BUT: The correct value is 483840
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.Sign up to join this community
This is because the default numeric type is
int, which on Arduino is just 16 bits (and signed).
So 48 * 70 * 144 is 0x76200 in hex, which truncated to 16 bits is 0x6200, or 25088. This calculation is done by the preprocessor, not the compiler, so doesn't know (or care) about the destination variable type.
You need to force the values to be calculated as unsigned long by appending
UL to them:
bytes = 48UL * 70UL * 144UL;