一个压缩算法

package algorithm;


public class Zigzag {
	// 对于所有整数,符号位放最后一位。 整数数值位不变;负数除符号位外,全部取反。
	public int int_to_compInt(int n) {
		return (n << 1) ^ (n >> 31);
	}

	//符号位迁移至第一位。正数数值位不变。负数数值位取反。
	public int comInt_to_int(int n) {
		return (n >>> 1) ^ -(n & 1);

	}

	public byte[] write_to_buffer(int comInt) 
	{
		int tmp=comInt;
		int len=0;
		while(tmp!=0) 
		{
			tmp=tmp>>>7;
			len++;
		}
		tmp=comInt;
		byte[] buffer=new byte[len];
		for (int i=0 ;i< len-1;i++) {
			
			buffer[i]=(byte)((tmp & 0x7f)|0x80);
			tmp=tmp>>>7;
		}
		buffer[len-1]=(byte)(tmp & 0x7f);
		return buffer;
	}
	
	public int read_from_buffer(byte[] buffer)
	{
		int result=0;
		int len=buffer.length;
		for(int i=len-1;i>=0;i--) 
		{
			result=(result<<7)^(buffer[i]&0x7f);
		}
		return result;
	}
	public static void main(String[] args) 
	{
		Zigzag zigzag = new Zigzag();
		int zigzagInt = zigzag.int_to_compInt(-589);
		byte[] comptBytes=zigzag.write_to_buffer(zigzagInt);
		int readBytes=zigzag.read_from_buffer(comptBytes);
		int ori=zigzag.comInt_to_int(readBytes);
		System.out.println(ori);
	}
}

  

posted on 2018-08-06 17:31  爱养花的码农  阅读(150)  评论(0)    收藏  举报