tim4dev
tim4dev

Reputation: 2987

Multiplication, division. What is wrong?

Simple operations. Calculate time delay.

const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

Arduino UNO printed in monitor console:

What is wrong?

Upvotes: 0

Views: 319

Answers (1)

Jacques Supcik
Jacques Supcik

Reputation: 659

300 * 1000 is expected to give 30'0000, or 0x493E0 in hexadecimal. But when you write (300 * 1000), the Arduino uses 16 bits signed integer arithmetic, so the result is truncated to 0x93E0 (or -27680 in decimal).

When you then divide by an unsigned long, the result is converted to unsigned long and this gives 0xFFFF'93E0 or 4'294'939'616 in decimal.

Divide by 30'000 and you get 143'164.

For V2 it is the same: (300 * 1000) = -27680 in 16 bit signed arithmetic and -27'680 / 30'000 gives 0.

Upvotes: 3

Related Questions