#include <iostream>
#include <cstdint>
// Function to encode an unsigned integer into a variable-length format
void encodeVarint(uint64_t value, std::ostream& output) {
do {
uint8_t byte = value & 0x7F;
value >>= 7;
byte |= ((value > 0) ? 1 : 0) << 7;
output.put(byte);
} while (value > 0);
}
// Function to decode a variable-length encoded unsigned integer
uint64_t decodeVarint(std::istream& input) {
uint64_t result = 0;
uint64_t shift = 0;
uint8_t byte;
do {
input.get(reinterpret_cast<char*>(&byte));
result |= (static_cast<uint64_t>(byte & 0x7F) << shift);
shift += 7;
} while (byte & 0x80);
return result;
}
int main() {
// Example Usage
uint64_t originalValue = 150;
std::cout << "Original Value: " << originalValue << std::endl;
// Encode the value and print the encoded bytes
std::cout << "Encoded Bytes: ";
encodeVarint(originalValue, std::cout);
std::cout << std::endl;
// Simulate receiving the encoded bytes and decode the value
std::cout << "Decoded Value: " << decodeVarint(std::cin) << std::endl;
return 0;
}