public
static
void
writeVInt
(
DataOutput
stream
,
int
i
)
throws
IOException
{
writeVLong
(
stream
,
i
)
;
}
/**
* Serializes a long to a binary stream with zero-compressed encoding.
* For -112 <= i <= 127, only one byte is used with the actual value.
* For other values of i, the first byte value indicates whether the
* long is positive or negative, and the number of bytes that follow.
* If the first byte value v is between -113 and -120, the following long
* is positive, with number of bytes that follow are -(v+112).
* If the first byte value v is between -121 and -128, the following long
* is negative, with number of bytes that follow are -(v+120). Bytes are
* stored in the high-non-zero-byte-first order.
*
* @param stream 保存序列化结果输出流
* @param i 被序列化的整数
* @throws java.io.IOException
*/
public
static
void
writeVLong
(
DataOutput
stream
,
long
i
)
throws
IOException
{
// 处于[-112,127]的整数
if
(
i
&
gt
;
=
-
112
&
amp
;
&
amp
;
i
&
lt
;
=
127
)
{
stream
.
writeByte
(
(
byte
)
i
)
;
return
;
}
// 计算情况2的第一个字节
int
len
=
-
112
;
if
(
i
&
lt
;
0
)
{
i
^=
-
1L
;
// take one's complement'
len
=
-
120
;
}
long
tmp
=
i
;
while
(
tmp
!=
0
)
{
tmp
=
tmp
&
gt
;
&
gt
;
8
;
len
--
;
}
stream
.
writeByte
(
(
byte
)
len
)
;
len
=
(
len
&
lt
;
-
120
)
?
-
(
len
+
120
)
:
-
(
len
+
112
)
;
// 输出后续字节
for
(
int
idx
=
len
;
idx
!=
0
;
idx
--
)
{
int
shiftbits
=
(
idx
-
1
)
*
8
;
long
mask
=
0xFFL
&
lt
;
&
lt
;
shiftbits
;
stream
.
writeByte
(
(
byte
)
(
(
i
&
amp
;
mask
)
&
gt
;
&
gt
;
shiftbits
)
)
;
}
}