View Javadoc
1   package edu.jiangxin.apktoolbox.convert.protobuf.unsupervised;
2   
3   import java.math.BigInteger;
4   import java.util.HashMap;
5   import java.util.Map;
6   
7   public class VarintUtils {
8   
9       /**
10       * 解码为有符号类型
11       *
12       * @param bigInteger
13       * @return
14       */
15      protected static BigInteger interpretAsSignedType(BigInteger bigInteger){
16          BigInteger i = bigInteger.and(new BigInteger("1"));
17          if (i.equals(new BigInteger("0"))) {
18              return bigInteger.divide(new BigInteger("2"));
19          }
20          return new BigInteger("-1").multiply(bigInteger.add((new BigInteger("1")).divide(new BigInteger("2"))));
21      }
22  
23  
24      /**
25       * 解码可变整数
26       *
27       * @param buffer
28       * @param offset
29       * @return
30       */
31      protected static Map<String, Object> decodeVarint(byte[] buffer, int offset) {
32          BigInteger res = new BigInteger("0");
33          int shift = 0;
34          byte bytes;
35  
36          int count = 0;
37          do {
38              if (offset >= buffer.length) {
39                  throw new RuntimeException("Index out of bound decoding varint");
40              }
41              count++;
42              bytes = buffer[offset++];
43  
44              BigInteger multiplier =  new BigInteger("2").pow(shift);
45              BigInteger thisByteValue = (new BigInteger(Long.toString(bytes & 0x7f))).multiply(multiplier);
46              shift += 7;
47              res = res.add(thisByteValue);
48          } while ((bytes & 0xff) >= 128 && count < 8);
49  
50          Map<String, Object> result = new HashMap<>(2);
51          result.put("value", res);
52          result.put("length", (shift / 7));
53          return result;
54      }
55  
56  }