Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.nio.charset.Charset;
- public class RLE{
- private static Byte[] StringToByteArray(String string) {
- byte[] bytes = string.getBytes(Charset.forName("ASCII"));
- Byte[] result = new Byte[bytes.length];
- for(int i = 0; i < bytes.length; i++)
- result[i] = bytes[i];
- return result;
- }
- public static void main(String []args){
- ArrayList<Byte> data = new ArrayList<Byte>(
- Arrays.asList(StringToByteArray("www"))
- );
- System.out.println("Entrada......: " + data);
- data = compressRLE(data, 2);
- System.out.println("Comprimido...: " + data);
- System.out.println("Descomprimido: " + DecompressRLE(data, 2));
- }
- private static ArrayList<Byte> compressRLE(ArrayList<Byte> data, int n) {
- ArrayList<Byte> result = new ArrayList<Byte>();
- int count = 0;
- Byte last = 0;
- for(Byte b : data) {
- if(b != last || count == 0xFF + n) {
- writeRLE(last, count, n, result);
- last = b;
- count = 1;
- } else {
- count++;
- }
- }
- writeRLE(last, count, n, result);
- return result;
- }
- private static ArrayList<Byte> DecompressRLE(ArrayList<Byte> data, int n) {
- ArrayList<Byte> result = new ArrayList<Byte>();
- int count = 0;
- Byte last = 0;
- for(Byte b : data) {
- if(count == n) {
- count = b + n;
- for(int i = 0; i < count; i++)
- result.add(last);
- count = 0;
- } else if (b != last) {
- for(int i = 0; i < count; i++)
- result.add(last);
- last = b;
- count = 1;
- } else {
- count++;
- }
- }
- return result;
- }
- private static void writeRLE(Byte b, int count, int n, ArrayList<Byte> result) {
- for(int i = 0; i < Math.min(count, n); i++)
- result.add(b);
- if(count >= n) {
- byte c = (byte)(count-n);
- result.add(c);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement