C++ Can';我的压缩算法无法正常工作

C++ Can';我的压缩算法无法正常工作,c++,algorithm,compression,C++,Algorithm,Compression,我正在使用一个函数将字符序列压缩为3位。我的字母表包含字母ATGCN。我正在输入一个测试字符串,并得到一个答案,它有正确的值,但也有一些我不期望的值。这是我的密码: #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; #define A1 0x00 //0000-0 000 #define T1

我正在使用一个函数将字符序列压缩为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;
}

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

数据
的类型从
字符
更改为
无符号字符
。在某些情况下,
data
有一个负值,因此当您将其转换为
int
以打印它时,它将被1填充。

如果您知道整数不会小于0,那么我建议您使用
无符号字符
40ffffffa052