c++ - 在 MSVC 中压缩后可能发生数据损坏? (C++)

标签 c++ visual-c++ visual-studio-2012 compression

我对 C++ 有点陌生,正在研究基本压缩。我在 MSVC(Windows 7,编译为 32 位控制台程序)中编写了下面的程序,它将具有 4 个可能值的 char 数组压缩为一个字节。我已经包含了检查中间二进制值的代码行。

(对于下面的长代码表示歉意,唯一包含的是 iostream)

程序运行时:

ABCD转换为11100100,根据我的编码表是正确的。 这会在我的系统上转换为 ASCII ý。

然而,在解码时,ý 变为 11101100,解码为“ADCD”!我已经尝试了一些其他的起始数组,并且损坏似乎只发生在数组中的第二个字符是“B”时,然后它被更改为“D”,或者如果有一个全是“B”的字符串"s,当备用的 "B"变为 "D"时。当放置在其他位置时,“B”不会损坏。

我很困惑为什么一位会出错,而且只针对特定的序列,如果有人能给我一些提示吗?

谢谢!

K

struct CompressedChar {
    int firstbit; 
    int secondbit; 
};


CompressedChar Encoder(char baseinput)
{
CompressedChar bitoutput;

switch (baseinput)
    {
    case 'A':
        bitoutput.firstbit = 0;
        bitoutput.secondbit = 0;
        break;
    case 'B':
        bitoutput.firstbit = 1;
        bitoutput.secondbit = 0;
        break;
    case 'C':
        bitoutput.firstbit = 0;
        bitoutput.secondbit = 1;
        break;
    case 'D':
        bitoutput.firstbit = 1;
        bitoutput.secondbit = 1;
        break;

    }   

return bitoutput;
}


char Decoder(int firstbit, int secondbit)
{
if (firstbit == 0)
{
    if (secondbit == 0)
        return 'A';
    else if (secondbit == 1)
        return 'C';
}

else if (firstbit == 1)
{
    if (secondbit == 0)
        return 'B';
    else if (secondbit = 1)
        return 'D';
}

return '0';
}

int main()
{
char a[4] = {'A', 'B', 'C', 'D'};

char output;


for (int i = 0; i < 8; i += 2)
{
    CompressedChar bitoutput;

    bitoutput = Encoder(a[(i/2)]);

    std::cout << bitoutput.firstbit;
    std::cout << bitoutput.secondbit;

    if (bitoutput.firstbit == 1)
        { output |= (1 << i); }
    else if (bitoutput.firstbit == 0)
        { output &= ~(1 << i);}

    if (bitoutput.secondbit == 1)
        { output |= (1 << (i + 1) ); }
    else if (bitoutput.firstbit == 0)
        { output &= ~(1 << (i + 1));}
}

std::cout << std::endl << output << std::endl;

char b[4];
int temp1, temp2;

for (int i = 0; i < 8; i += 2)
{
    temp1 = (output >> i) & 1;
    temp2 = (output >> (i + 1)) & 1;

    std::cout<< temp1;
    std::cout<< temp2;

    b[i/2] = Decoder(temp1, temp2);
} 

    std::cout<< std::endl;
for (int j = 0; j < 4; j ++)
{
    std::cout << b[j];
}

std::cout << std::endl;
return 0;
}

最佳答案

这是因为它被初始化为 0xCC。您可能还犯了一个错误,上面写着“else if (bitoutput.firstbit == 0)”应该是 secondbit。还要使输出 unsigned char 安全/清晰。

关于c++ - 在 MSVC 中压缩后可能发生数据损坏? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179091/

相关文章:

c++ - 使用 fscanf 时将宽度作为变量

c++如何设置更严格的异常(错误)规则?

windows - (Windows) 如何锁定所有应用程序(资源管理器、任务管理器等)并仅使浏览器处于事件状态?

c# - 在 ClickOnce 部署中将多个应用程序打包在一起

c++ - Jenkins 构建在 Windows 上因 GitLockFailedException 而失败

c++ - 使用佳能 EDSDK 时出现 undefined reference 错误

c++ - 如何取消定义 Visual Studio 2012 的系统定义?

c++ - 在 C++ 的 SFML 中居中​​形状/对象

c++ - mipsel-linux-objdump 无法识别 mipsel-linux-g++ 对象

visual-c++ - 如何清除vc++paint中所有以前绘制的图形?