I have this code which provides an erroneous unsigned long number.


char buff[100];

int unsigned long bytes;

bytes = 48 * 70 * 144;

sprintf(buff,"%lu bytes\n", bytes);


OUTPUT: 20088 bytes

BUT: The correct value is 483840


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;
  • Thank you for your time, this was extremely useful. Dec 23 '20 at 12:35
  • It's even sufficient to force one of the values to be unsigned long. bytes = 48UL*20*144; Dec 23 '20 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.