aboutsummaryrefslogtreecommitdiff
path: root/java/com/xagasoft/gats/Integer.java
blob: 7da12d4f6b85d50c0bc98952f72e35908755bb0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.xagasoft.gats;

import java.io.OutputStream;
import java.io.InputStream;

public class Integer extends Type
{
	public int getType()
	{
		return Type.INTEGER;
	};

	/**
	 * Possible TODO: have this return a Number, and construct either a Long
	 * or BigInteger when appropriate.
	 */
	public static long readPackedInt( InputStream is )
		throws java.io.IOException
	{
		int b;
		long rOut = 0;
		boolean bNeg;
		
		b = is.read();
		bNeg = (b&0x40) == 0x40;
		rOut |= b&0x3F;
		int c = 0;
		while( (b&0x80) == 0x80 )
		{
			b = is.read();
			rOut |= (long)(b&0x7F) << (6+7*(c++));
		}
		if( bNeg )
			return -rOut;
		return rOut;
	}

	public static void writePackedInt( OutputStream os, long iIn )
		throws java.io.IOException
	{
		int b;

		if( iIn < 0 )
		{
			iIn = -iIn;
			b = (int)(iIn&0x3F);
			if( iIn > b )
				b |= 0x80 | 0x40;
			else
				b |= 0x40;
		}
		else
		{
			b = (int)(iIn&0x3F);
			if( iIn > b )
				b |= 0x80;
		}
		os.write( b );
		iIn = iIn >> 6;

		while( iIn > 0 )
		{
			b = (int)(iIn&0x7F);
			if( iIn > b )
				b |= 0x80;
			os.write( b );
			iIn = iIn >> 7;
		}
	}
};