无法使我的压缩算法正常运行

时间:2013-11-21 16:55:59

标签: c++ algorithm compression

我正在使用一个函数将一系列字符压缩为3位。我的字母包含字母ATGCN。我正在输入测试字符串并获得具有正确值的答案,但也有一些我没想到的值。这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

#define A1    0x00 //0000-0 000
#define T1    0x01 //0000-0 001
#define G1    0x02 //0000-0 010
#define C1    0x03 //0000-0 011
#define N1    0x04 //0000-0 100

void bitcompress(int value, int bits, int end_flag);
int getHex(const char letter);

int main(int argc, const char * argv[])
{
    string test = "GATGATGG";//compresses to 0x40a052 with my definitions
    for (int i=0; i<test.size(); i++) {
        int val = getHex(test.at(i));
        bitcompress(val, 3, 0);
    }

    return 0;
}

void bitcompress(int value, int bits, int end_flag)
{
    static char data    = 0;
    static int bitsused = 0;

    int bytesize = 8;
    int shift    = bytesize - bitsused - bits;

    //cout << "bitsused = " << bitsused << endl;
    //cout << "shift    = " << shift << endl << endl;

    if(shift >= 0) {
        data        |= (value << shift);
        bitsused    += bits;
        if(bitsused == bytesize) {
            cout << hex << setw(2) << setfill('0') << (int)data;
            data     = 0;
            bitsused = 0;
        }
    }

    else {
        data |= (value >> -shift);
        cout << hex << setw(2) << setfill('0') << (int)data;
        data  = 0;
        shift = bytesize + shift;

        if(shift >= 0) {
            data    |= (value << shift);
            bitsused = bytesize - shift;
        } else {
            data    |= (value >> -shift);
            cout << hex << setw(2) << setfill('0') << (int)data;
            data     = 0;
            shift    = bytesize + shift;
            data    |= (value << shift);
            bitsused = bytesize - shift;
        }
    }

    if(end_flag && bitsused != 0)
        cout << hex << setw(2) << setfill('0') << (int)data;
}

int getHex(const char letter) {
    if (letter == 'A')
        return (int)A1;
    else if (letter == 'T')
        return (int)T1;
    else if (letter == 'G')
        return (int)G1;
    else if (letter == 'C')
        return (int)C1;
    else
        return (int)N1;
}

我期待0x40a052,但输出:

40ffffffa052

我不确定所有f的来自哪里。如果您在if语句之后注释掉所有cout并取消之前的注释,则会看到shift和bitsused值是正确的。但是,如果你将它们全部取消注释,则“shift”值将获得fffffffe的赋值,而不是-2(可以通过在if语句下面注释cout来看到)。我觉得问题可能与输出到流有关,但我不确定。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

data的类型从char更改为unsigned char。在某些时候,data具有负值,因此当您将其强制转换为int进行打印时,它会左侧填充1。

相关问题