让我们回顾一下维基百科页面上的算法:
-
取整数的二进制表示
-
将其分为7位组,值最高的组将具有较少的
-
将这七位作为一个字节,将除最后一位外的所有msb(最有效位)设置为1;将最后一位保留为0
我们可以实现这样的算法:
public static byte[] variableLengthInteger(int input) {
// first find out how many bytes we need to represent the integer
int numBytes = ((32 - Integer.numberOfLeadingZeros(input)) + 6) / 7;
// if the integer is 0, we still need 1 byte
numBytes = numBytes > 0 ? numBytes : 1;
byte[] output = new byte[numBytes];
// for each byte of output ...
for(int i = 0; i < numBytes; i++) {
// ... take the least significant 7 bits of input and set the MSB to 1 ...
output[i] = (byte) ((input & 0b1111111) | 0b10000000);
// ... shift the input right by 7 places, discarding the 7 bits we just used
input >>= 7;
}
// finally reset the MSB on the last byte
output[0] &= 0b01111111;
return output;
}
您可以看到它为维基百科页面上的示例工作。
here
你也可以插入你自己的价值观,并尝试在线。