The result of 512*1024 becomes 0

actually when you have a long and an int, the int is promoted first into the larger storage (so long in that case), the multiplication is done using long, and then the result is transformed (with very clear rules) into the destination type of your variable.

Also important to know that

  • if one of the operand is unsigned and the other is signed, then the later is transformed in place into the equivalent memory representation as unsigned (ie the bits are interpreted as if the value was unsigned) for the operation.
  • if you store an unsigned value into a signed value, the bits are interpreted directly.
  • if the operant fit on a byte, it is transformed into the (signed/unsigned) int (bit equivalent) representation before doing the math.

that leads to interesting results if you are not careful. For example, on a UNO this code

void setup() {
  Serial.begin(115200); Serial.println();
  const uint8_t b = 255;
  uint8_t   x1 = b * -2; Serial.print(x1); Serial.print("\t= 0b"); Serial.println(x1, BIN);
  int16_t   x2 = b * -2; Serial.print(x2); Serial.print("\t= 0b"); Serial.println(x2, BIN);
  uint16_t  x3 = b * -2; Serial.print(x3); Serial.print("\t= 0b"); Serial.println(x3, BIN);
  int32_t   x4 = b * -2; Serial.print(x4); Serial.print("\t= 0b"); Serial.println(x4, BIN);
  uint32_t  x5 = b * -2; Serial.print(x5); Serial.print("\t= 0b"); Serial.println(x5, BIN);
}

void loop() {}

will print to the Serial monitor

2	       = 0b10
-510 	   = 0b11111111111111111111111000000010
65026  	   = 0b1111111000000010
-510	   = 0b11111111111111111111111000000010
4294966786 = 0b11111111111111111111111000000010

quite different values !!

2 Likes