aboutsummaryrefslogtreecommitdiff
path: root/java/com/xagasoft/gats/GatsInteger.java
blob: 1093ab2888e08f501208b61ffc76c58f9116f358 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.xagasoft.gats;

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

public class GatsInteger extends GatsObject
{
	private long iValue = 0;

	public GatsInteger()
	{
	}

	public GatsInteger( long iValue )
	{
		this.iValue = iValue;
	}

	public long getValue()
	{
		return iValue;
	}

	public void setValue( long iValue )
	{
		this.iValue = iValue;
	}

	public int getType()
	{
		return GatsObject.INTEGER;
	};

	public void read( InputStream is, char cType ) throws java.io.IOException

	{
		iValue = readPackedInt( is );
	}

	public void write( OutputStream os ) throws java.io.IOException
	{
		os.write( (int)'i' );
		writePackedInt( os, iValue );
	}

	/**
	 * 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;
		}
	}
};