在编码数字时,有无符号的LEB128和有符号的LEB128之间是有区别的。
无符号的LEB128编码方式用于编码正整数,而有符号的LEB128编码方式用于编码有正负之分的整数。
下面是使用C++示例代码展示如何编码和解码无符号LEB128和有符号LEB128:
#include
#include
// 编码无符号LEB128
std::vector encodeUnsignedLEB128(unsigned int value) {
std::vector result;
do {
unsigned char byte = value & 0x7F;
value >>= 7;
if (value != 0) {
byte |= 0x80;
}
result.push_back(byte);
} while (value != 0);
return result;
}
// 解码无符号LEB128
unsigned int decodeUnsignedLEB128(const std::vector& bytes) {
unsigned int result = 0;
int shift = 0;
for (const auto& byte : bytes) {
result |= (byte & 0x7F) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
break;
}
}
return result;
}
// 编码有符号LEB128
std::vector encodeSignedLEB128(int value) {
std::vector result;
bool more = true;
while (more) {
unsigned char byte = value & 0x7F;
value >>= 7;
if ((value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0)) {
more = false;
} else {
byte |= 0x80;
}
result.push_back(byte);
}
return result;
}
// 解码有符号LEB128
int decodeSignedLEB128(const std::vector& bytes) {
int result = 0;
int shift = 0;
unsigned char byte = bytes[0];
while (true) {
result |= (byte & 0x7F) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
break;
}
byte = bytes[shift / 7];
}
if ((byte & 0x40) != 0) {
result |= - (1 << shift);
}
return result;
}
int main() {
unsigned int unsignedValue = 123456;
std::vector encodedUnsigned = encodeUnsignedLEB128(unsignedValue);
unsigned int decodedUnsigned = decodeUnsignedLEB128(encodedUnsigned);
std::cout << "Unsigned Value: " << unsignedValue << std::endl;
std::cout << "Encoded Unsigned: ";
for (const auto& byte : encodedUnsigned) {
std::cout << +byte << " ";
}
std::cout << std::endl;
std::cout << "Decoded Unsigned: " << decodedUnsigned << std::endl;
int signedValue = -123456;
std::vector encodedSigned = encodeSignedLEB128(signedValue);
int decodedSigned = decodeSignedLEB128(encodedSigned);
std::cout << "Signed Value: " << signedValue << std::endl;
std::cout << "Encoded Signed: ";
for (const auto& byte : encodedSigned) {
std::cout << +byte << " ";
}
std::cout << std::endl;
std::cout << "Decoded Signed: " << decodedSigned << std::endl;
return 0;
}
上述代码中,encodeUnsignedLEB128
函数用于编码无符号LEB128,decodeUnsignedLEB128
函数用于解码无符号LEB128。encodeSignedLEB128
函数用于编码有符号LEB128,decodeSignedLEB128
函数用于解码有符号LEB128。
在main
函数中,示例了如何使用这些函数进行编码和解码,并打印结果。运行程序将会输出编码结果和解码结果。
上一篇:编码数据集数组时遇到问题。