1

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

CODE:

char buff[100];

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

ocrdu
  • 1,673
  • 2
  • 9
  • 22

1 Answers1

2

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;
Majenko
  • 103,876
  • 5
  • 75
  • 133