aboutsummaryrefslogtreecommitdiff
path: root/php/int.php
blob: 478af7334f9b401d60afbc611bfc3ccea0a3b703 (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
103
104
105
106
107
108
<?php

/*
function writeInta( $iIn )
{
	$ret = "";
	if( $iIn < 0 )
	{
		$iIn = -$iIn;
		$b = ($iIn&0x3f);
		if( $iIn > $b )
			$b |= 0x80 | 0x40;
		else
			$b |= 0x40;
	}
	else
	{
		$b = ($iIn&0x3f);
		if( $iIn > $b )
			$b |= 0x80;
	}

	$ret .= chr( $b );
	$iIn = $iIn >> 6;

	while( $iIn > 0 )
	{
		$b = ($iIn&0x7f);
		if( $iIn > $b )
			$b |= 0x80;
		$ret .= chr( $b );
		$iIn = $iIn >> 7;
	}

	return $ret;
} */

function writeInt( $iIn )
{
	$ret = "";
	if( gmp_cmp( $iIn, 0 ) < 0 )
	{
		$iIn = gmp_mul( $iIn, -1 );
		$b = gmp_intval( gmp_and( $iIn, 0x3f ) );
		if( gmp_cmp( $iIn, $b ) > 0 )
			$b |= 0x80 | 0x40;
		else
			$b |= 0x40;
	}
	else
	{
		$b = gmp_intval( gmp_and( $iIn, 0x3f ) );
		if( gmp_cmp( $iIn, $b ) > 0 )
			$b |= 0x80;
	}

	$ret .= chr( $b );
	$iIn = gmp_div( $iIn, 64 );

	while( gmp_cmp( $iIn, 0 ) > 0 )
	{
		$b = gmp_intval( gmp_and( $iIn, 0x7f ) );
		if( gmp_cmp( $iIn, $b ) > 0 )
			$b |= 0x80;
		$ret .= chr( $b );
		$iIn = gmp_div( $iIn, 128 );
	}

	return $ret;
}

function readInt( $sIn, &$pos )
{
	$neg = false;

	$b = ord($sIn[$pos++]);
	if( ($b&0x40) == 0x40 )
		$neg = true;
	$iOut = gmp_init( $b&0x3f );
	$mult = gmp_init( 64 );
	while( ($b&0x80) )
	{
		$b = ord($sIn[$pos++]);
		$iOut = gmp_or( $iOut, gmp_mul( $b&0x7f, $mult ) );
		$mult = gmp_mul( $mult, 128 );
	}
	if( $neg == true )
		$iOut = gmp_mul( $iOut, -1 );

	return $iOut;
}

function teststr( $str )
{
	$pos = 0;
	$enc = writeInt( $str );
	$out = gmp_strval( readInt( $enc, $pos ) );
	print( $str . " => " . $out );
	if( $out == $str )
		print(", correct.\n");
	else
		print(", incorrect.\n");
}
//print( bin2hex( writeInt("3898993999921") ) . "\n" );
teststr("-7");


?>