Unsigned Long multiplication

Hi,

i might found a bug regarding multiplication of unsigned long variables in the Arduino 1.0 IDE:

unsigned long xyz = 60 * 1000;
Serial.println(xyz);

results in: 4294961760

I expected 60000 as result.

The code should not behave like this, right?

The code should not behave like this, right?

Wrong.

Try

unsigned long x = 60;
unsigned long y = 1000;
unsigned long xy = x * y;

How does that look?

This results in 60000.
When i replace x or y with a number (unsigned long xy = x * 1000;), it results in 60000 too.
Buy when i replace both variables it results in 4294961760.

Buy when i replace both variables it results in 4294961760.

Because they're "int"s, and so signed.
Signed times signed is signed, even if the data type is wider.

Ahh i got it now.

int is from -32,767 to 32,767.
60 * 1000 is out of this range, so the int "overflows".

When i typecast them as unsigned long, it's working!

 unsigned long xyz = (unsigned long) 60 * (unsigned long) 1000;

A short-cut is to use the integer constant suffixes.

unsigned long xyz = 60UL * 1000UL;

kduin:
60 * 1000 is out of this range, so the int "overflows".

Not really.

60,000 can be stored within an int, so it stores it as 0xEA60. The problem is it's assumed to be signed, therefore 0xEA60 is recognized as -5536. You then tell it to store it in an unsigned long, so it has to expand the sign bit through the remaining data to remain consistent with the two's complement system, turning it into 0xFFFFEA60. If you convert that to decimal, you get the value that you see.