Weird Output for Printf Unsigned Long

时间:2017-04-10 02:59:09

标签: c printf multiplication 16-bit

This one is simple.

printf("%lu\n", (unsigned long)(320 * 200));

That line of code prints out "4294965760". That is definitely NOT equal to 360 * 200. What's wrong with it?

I am using Digital Mars C compiler in 16 bit medium memory model.

2 个答案:

答案 0 :(得分:4)

On a 16-bit system, if sizeof(int) == 2, then 320 * 200, which is equal to 64000, is too big for a signed int (range ±32,767 — and usually -32,768 too, but in theory it varies by platform). So, you have arithmetic overflow. The cast doesn't affect the multiplication; it only affects what happens to the result of the multiplication.

You'd do better with:

printf("%lu\n", 320UL * 200UL);

That forces the constants to unsigned long.

答案 1 :(得分:-1)

I just tried this in my code and I got 64000. Maybe the problem is that 320*200 is a signed number! And when you cast it, they have some problem with it at bits level? Try

unsigned long x = 320*200;
printf("%lu\n", x);
//64000 =                      0b1111101000000000
//4294965760 = 0b11111111111111111111101000000000

See that the first bits match! So it's probably problem of cast.