Multiplication of two int's gets negative

左心房为你撑大大i 提交于 2019-12-02 00:17:06

See http://en.wikipedia.org/wiki/Arithmetic_overflow

To fix in java, try using a long instead.

int progress = (int) ((byte_counter * 100L) / size);

or reverse order of operations

int progress = (int) (((float) byte_counter) / size) * 100);

21476160 * 100 = 2 147 616 000 is greater than 2 147 483 647, the max int.

You're overflowing.

Use long for your calculations.

2^31-1 = 2147483647  < 21476160 * 100 = 2147616000

You should use a long -- 2147760000 in binary is 10000000 00000100 00110111 10000000 and since the most significant bit is 1 it is interpreted as a negative number.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!