Created
February 11, 2018 07:46
-
-
Save PeraSite/87999b9b67f740d1ad341e4d75fcbbf6 to your computer and use it in GitHub Desktop.
Compress multiple int to one int
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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