将可变长度字节值转换为整数

时间:2013-11-26 17:56:42

标签: java byte variable-length

给定以下格式的输入字节流,是否有更好的方法来提取整数值?

The low order 7 bits of a byte to represent the value or part of the value
The high order bit is an "escape" or "continuation" bit

这样:

0x7F           0111_1111                      127 (0x7F = 0111_1111)
0x81 0x7F      1000_0001  0111_1111           255 (0xFF = 1111_1111)
0x82 0x80 0x00 1000_0010  1000_0000 0000_0000 32768 (0x8000 = 1000_0000_0000_0000)

目前我正在使用:

do {
  in.read(b, 0, 1); // read next byte
  intval = (intval * 0x80) + (b[0] & 0x7F);
} while ((b[0] & 0x80) == 0x80);

0 个答案:

没有答案