用于adobe的ascii85解码器算法在某些情况下失败

时间:2014-12-15 14:33:12

标签: c++ algorithm decode ascii85

我正在尝试用c ++开发一个Ascii85解码器,以解析adobe illustrator文件(* ai)中的位图文件。

我在java here中找到了一个算法,我试图用c ++重写它。

问题是我遇到了一些情况,我的编码文本没有被正确解码。例如,如果字符“a”是我的字符串中的第7个和最后一个字符(在编码之前),则将其解码为“`”,这是ascii表中的前一个字符。这很奇怪,因为我试图手动计算算法,结果我得到“`”。我想知道算法中是否存在错误,或者它是否是adobe ascii85解码的正确算法。

这是我的代码:

#include <QCoreApplication>
#include <stdio.h>
#include <string.h>
#include <QDebug>

// returns 1 when there are no more bytes to decode
// 0 otherwise
int decodeBlock(char *input, unsigned char *output, unsigned int inputSize) {
    qDebug() << input << output << inputSize;
    if (inputSize > 0) {
        unsigned int bytesToDecode = (inputSize < 5)? inputSize : 5;

        unsigned int x[5] = { 0 };
        unsigned int i;
        for (i = 0; i < bytesToDecode; i++) {
            x[i] = input[i] - 33;
            qDebug() << x[i] << ", i: " << i;
        }

        if (i > 0)
            i--;

        unsigned int value =
                x[0] * 85 * 85 * 85 * 85 +
                x[1] * 85 * 85 * 85 +
                x[2] * 85 * 85 +
                x[3] * 85 +
                x[4];

        for (unsigned int j = 0; j < i; j++) {
            int shift = 8 * (3 - j); // 8 * 3, 8 * 2, 8 * 1, 8 * 0
            unsigned char byte = (unsigned char)((value >> shift) & 0xff);
            printf("byte: %c, %d\n", byte, byte);
            *output = byte;
            output++;
        }
    }

    return inputSize <= 5;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    char x__input[] = "<~FE1f+@;K?~>";

    unsigned char x__output[128] = { 0 };

    char *input = x__input + 2;
    unsigned int inputSize = (unsigned int)strlen(input);
    inputSize -= 2;

    unsigned char *output = x__output;

    printf("decoding %s\n", input);
    for (unsigned int i = 0; i < inputSize; i += 5, input += 5, output += 4)
        if(decodeBlock(input, output, inputSize - i))
            break;

    printf("Output is: %s\n", x__output);

    return a.exec();
}

1 个答案:

答案 0 :(得分:2)

当inputSize不是5 ??

的倍数时会发生什么
    unsigned int bytesToDecode = (inputSize < 5)? inputSize : 5;

你假设bytesToDecode是5,而有些字节有未知值

因此,当你的角色是第7位的最后一个角色时,上述条件为真。

如果输入不是5的倍数,那么它必须用值&#34; u&#34;填充。 有关编码/解码过程的更多详细信息,请查看维基百科页面,其中有很好的解释:

http://en.wikipedia.org/wiki/Ascii85#Example_for_Ascii85