Skip to content

Instantly share code, notes, and snippets.

@PeraSite
Created February 11, 2018 07:46
Show Gist options
  • Select an option

  • Save PeraSite/87999b9b67f740d1ad341e4d75fcbbf6 to your computer and use it in GitHub Desktop.

Select an option

Save PeraSite/87999b9b67f740d1ad341e4d75fcbbf6 to your computer and use it in GitHub Desktop.
Compress multiple int to one int
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IntCompressor {
public static int compress(int... data) {
int[] compressedArr = new int[data.length - 1];
for (int i = 0; i <= data.length - 2; i++) {
if (i == 0) compressedArr[0] = compressNumber(data[0], data[1]);
else compressedArr[i] = compressNumber(data[i + 1], compressedArr[i - 1]);
}
int compressed = compressedArr[compressedArr.length - 1];
if (compressed < 127)
throw new InvalidParameterException("Input data is too big");
return compressed;
}
public static int[] decompress(int compressed) {
List<Integer> decompressed = new ArrayList<>();
while (compressed > 127) {
int[] arr = decompressNumber(compressed);
if (arr[1] < 127)
decompressed.add(arr[1]);
decompressed.add(arr[0]);
compressed = arr[1];
}
Collections.reverse(decompressed);
int[] array = new int[decompressed.size()];
for (int i = 0; i < decompressed.size(); i++) array[i] = decompressed.get(i);
return array;
}
public static int compressNumber(int small, int large) {
return ((large << 7) + small);
}
public static int[] decompressNumber(int data) {
int large = data >> 7;
int small = data - (large << 7);
return new int[]{small, large};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment