Multiplication error, dont know why

Hi, this is my code:

void setup() {
Serial.begin(9600);
}

void TestMulti(uint8_t Width, uint8_t Height){
  uint8_t sizeXMultiY = (uint8_t)((uint8_t)Width*(uint8_t)Height);
  String info = "TestMulti: sizeXMultiY = ";
  info = info + (uint8_t)sizeXMultiY;
  Serial.print(info);
}

void loop() {

TestMulti(84UL, 6UL);
delay(500);
}

And im still getting "TestMulti: sizeXMultiY = 248" and have no idea what am I doing wrong. As you can right now I, trying to cast everything to uint8_t and even 84UL, 6UL instead of 84, 6, but it gives me no results...

OK, looks like an error with data types - uint8_t is 0-255 ofc... So just changed uint8_ts to unasigned ints and it works, sorry for taking your time :)

You need to learn about types and how much each type can hold. uint8_t is an 8 bit type, so it only has a range of 0 - 255. If you go over that range then the value rolls over and the difference is taken.

84*6 = 504. But you are seeing 248, why is this? Well 504(what the value would have been) - 256 (8 bit container) = 248.

change all the uint8_t to uint16_t (16 bit) and you will get the correct answer. You also have uint32_t and uint64_t to experiment with.

I agree with HazardsMind. You are doing all your calculations with uint8_t but you are passing in unsigned long values which are much larger. Bits are being chopped off and that's why you get unexpected results.

The maximum value that can be represented by 8 bits is (2^8)-1 = 255. Any result greater than that such as in your example (84 * 6 = 504) will not give you what you expect. Use a larger data type in your TestMutli() function and you'll see the answers you expect.

void TestMulti(uint8_t Width, uint8_t Height){
  uint8_t sizeXMultiY = (uint8_t)((uint8_t)Width*(uint8_t)Height);

Why do you feel it necessary to cast a uint8_t to a uint8_t?

void TestMulti(uint8_t Width, uint8_t Height){
  uint8_t sizeXMultiY = (uint8_t)((uint8_t)Width*(uint8_t)Height);
  String info = "TestMulti: sizeXMultiY = ";
  info = info + (uint8_t)sizeXMultiY;
  Serial.print(info);
}

This is incredibly unreadable. Get rid of all the casts. You also don’t need to tack UL onto your constants. Here, I fixed it for you:

void setup()
{
  Serial.begin (115200);
}

void TestMulti (int Width, int Height)
  {
  int sizeXMultiY = Width * Height;
  Serial.print   ("TestMulti: sizeXMultiY = ");
  Serial.println (sizeXMultiY);
  }

void loop() 
  {
  TestMulti (84, 6);
  delay (500);
  }

(Alert: new baud rate).

I have a page about integer overflow.