简体   繁体   English

编码/解码问题

[英]encoding / decoding issue

I have a issue with my code below which does encoding of a vector of long into a string by storing the differences of the sequence.我的下面的代码有一个问题,它通过存储序列的差异将 long 向量编码为字符串。

The encode / decode works fine as long as the value is same or below 2^30 Any value above it, the logic fails.只要值等于或低于 2^30,编码/解码就可以正常工作。任何高于它的值,逻辑都会失败。 Note that the sizeof(long) is 8 bytes.请注意,sizeof(long) 是 8 个字节。

static std::string encode(const std::vector<long>& path) {
    long lastValue = 0L;
    std::stringstream result;

    for (long value : path) {
        long delta = value - lastValue;
        lastValue = value;

        long var = 0;

        // Shift the delta value left by 1 bit and encode each 5-bit chunk into a character
        for (var = delta < 0 ? ~(delta << 1) : delta << 1; var >= 32L; var >>= 5) {
            result << (char)((32L | var & 31L) + 63L);  //char is getting written to result stringstream
        }

        // Encode the last 5-bit chunk into a character
        result << (char)(var + 63L); // char is getting written to result stringstream
    }

    std::cout << std::endl;
    return result.str();
}
static std::unique_ptr<std::vector<long>> decode(const std::string& encoded) {
    auto  decoded = std::make_unique<std::vector<long>>();
    long last_val = 0;    
    int index = 0;

    while (index < encoded.length()) {
        int shift = 0;
        long current = 1;
        int c;

        do {
            c = encoded[index++] - 63 - 1;
            current += c << shift;
            shift += 5;
        } while (c >= 31);

        long v = ( (current & 1) == 0 ? current >> 1 : ~(current >> 1) );
        last_val += v;
        decoded->push_back(last_val);
    }

    return std::move(decoded);
}

Can someone please provide insight what might be going wrong?有人可以提供见解可能出了什么问题吗?

inside the decode function, it was required to declare c as "long" and not as "int".在解码 function 中,需要将 c 声明为“long”而不是“int”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM