2

I'm currently coding a little download manager and I get a funny output when I try to calculate the download-progress in percent. This is what i use to calculate it:

int progress = (byte_counter * 100) / size;
System.out.println("("+byte_counter+" * 100) = "+(byte_counter * 100)
  +" / "+size+" = "+progress);

byte-counter is an int (it counts the total bytes read from the InputStream) and size is the length of the downloaded file in bytes.

This works great with small downloads. But when i get to bigger files (40MB) it starts making funny things. The Output for the calculation looks like this:

[...]
(21473280 * 100) = 2147328000 / 47659008 = 45
(21474720 * 100) = 2147472000 / 47659008 = 45
(21476160 * 100) = -2147351296 / 47659008 = -45
(21477600 * 100) = -2147207296 / 47659008 = -45
[...]

I don't know why, but the calculation gets negative. Since an normal Integer should be fine with numbers till 231-1, this shouldn't be the problems root. But what am I missing?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111

4 Answers4

7

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);
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • I tried that, the problem is, that the result of the first calculation `(byte_counter * 100)` is never saved in any variable (should just be in memory). So I'm not sure where to specify the used data type. – Lukas Knuth May 18 '11 at 20:52
  • 1
    @Lucas, the `100L` notation above specifies a `long` value of 100. This will cause `byte_counter` to be promoted to a `long` before the multiplication happens. In general, you can always force `byte_counter` to be promoted to a `long` by doing `((long) byte_counter)`. – Mike Samuel May 18 '11 at 20:54
5

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

You're overflowing.

Use long for your calculations.

Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
3
2^31-1 = 2147483647  < 21476160 * 100 = 2147616000
dfb
  • 13,133
  • 2
  • 31
  • 52
2

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.

Sai
  • 3,819
  • 1
  • 25
  • 28