Created
June 27, 2012 13:10
-
-
Save anonymous/3003981 to your computer and use it in GitHub Desktop.
Variable Byte Code(sample)
This file contains 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 gnu.trove.TByteArrayList; | |
import java.util.Arrays; | |
public class VariableByte { | |
public static byte[] encode(int[] numbers) { | |
TByteArrayList result = new TByteArrayList(numbers.length * 4); | |
TByteArrayList buf = new TByteArrayList(); | |
for(int number : numbers){ | |
buf.clear(); | |
int num = number; | |
while (true) { | |
byte b = (byte)(num % 128); | |
buf.insert(0, b); | |
num = num >> 7; | |
if(num <= 0){ | |
break; | |
} | |
} | |
byte last = (byte)(buf.get(buf.size() - 1) + (byte)0x80); | |
buf.set(buf.size() - 1, last); | |
result.add(buf.toNativeArray()); | |
} | |
return result.toNativeArray(); | |
} | |
public static int[] decode(byte[] encoded){ | |
int[] buf = new int[encoded.length]; | |
int num = 0; | |
int index = 0; | |
for(int i = 0 ; i < encoded.length ; i++){ | |
byte b = encoded[i]; | |
if (b >= 0) { | |
num = (num << 7) + b; | |
} else { | |
buf[index++] = (num << 7) + (byte)(b - (byte)0x80); | |
num = 0; | |
} | |
} | |
return Arrays.copyOfRange(buf, 0, index); | |
} | |
public static void main(String[] args) { | |
int[] numbers = new int[args.length]; | |
System.out.println("origin size:" + (numbers.length * 4)); | |
for(int i = 0 ; i < args.length ; i++){ | |
numbers[i] = Integer.parseInt(args[i]); | |
System.out.print(numbers[i] + " "); | |
} | |
System.out.println(); | |
byte[] encoded = encode(numbers); | |
System.out.println("encoded size:" + (encoded.length)); | |
for(int i = 0 ; i < encoded.length ; i++){ | |
System.out.print(encoded[i] + " "); | |
if(encoded[i] >= 0){ | |
System.out.print(" "); | |
}else{ | |
System.out.print(" / "); | |
} | |
} | |
System.out.println(); | |
int[] decoded = decode(encoded); | |
System.out.println("decoded size:" + (decoded.length * 4)); | |
for(int i = 0 ; i < decoded.length ; i++){ | |
System.out.print(decoded[i] + " "); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment