0

I have a file that I want to split into 100 pieces.
The file size is 257019 bytes.
When running my splitter code below I get 99 parts with a size of 2545 byte and the last 100'th part is 5064 byte.

I need help to figure out how to make the first 99 parts having the same size and the last 100'th part having the leftover bytes that is equal or lower then 2545.

int partSize;
for(partSize=1 ;partSize< 257019; partSize++){
   if((int) Math.ceil(257019 / partSize) == 100){
     break;
   }
}

int totalparts = (int) Math.ceil(257019 / partSize); // =100
Erik
  • 5,039
  • 10
  • 63
  • 119

2 Answers2

4
int fileSize = 257019;
int partSize = Math.ceil( ((double)fileSize) / 100);
int lastPacket = 257019 - (99 * partSize);

In this case:

int partSize = 2571;
int lastPacket = 257019 - 254529 = 2490 < 2571

The original problem with your code:

(int) Math.ceil(257019 / partSize) == 100

is that 257019 / partSize is evaluated before Math.ceil is evaluated. If you divide an integer by an integer, the result is automatically an integer. The default behavior of an integer is to omit everything but the decimal itself, so it will automatically "Math.floor()" it.

bas
  • 1,678
  • 12
  • 23
3
int partSize = totalSize / 100;
if ((totalSize % 100) != 0) {
    partSize++;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Can you explain what it does compared to @bas answer that worked grate – Erik Jul 30 '13 at 18:40
  • 2
    if partSize cannot be fully divided by 100, it will leave a remainder. The `modulus` (`%`) operator checks if there is a remainder. If there is a remainder, then your `partSize` will need to be one size larger (since the last packet does otherwise not fit). This is a valid and working approach, though unnecessary technical imho. – bas Jul 30 '13 at 19:08
  • Floating point arithmetic doesn't return exact results. You might end up with rounding errors. Integer arithmetic is fast and precise. – JB Nizet Jul 30 '13 at 21:32
  • With that comment isn't @bas answer only wrong if I was to use the decimal value of the floating point [reference](http://stackoverflow.com/questions/1661273/floating-point-arithmetic-not-producing-exact-results-in-java) – Erik Aug 03 '13 at 05:44
  • `%` works with integers, so there would be no need for the `(double)` conversion. The double conversion in my original answer would only be able to cause errors if the value of fileSize is extremely large. The size that does not yet exist on harddisks. – bas Aug 03 '13 at 10:32