我正在使用一个函数将一个字符序列压缩成 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 和 bitused 值是正确的。但是,如果您将它们全部取消注释,则“shift”值将获得 fffffffe 的赋值,而不是 -2(可以通过注释掉 if 语句下方的 cout 来看到)。我觉得这个问题可能与输出到流有关,但我不确定。任何帮助将不胜感激!
最佳答案
将 data
的类型从 char
更改为 unsigned char
。在某些时候,data
有一个负值,所以当您将它转换为 int
来打印它时,它会在左侧填充 1。
关于c++ - 无法让我的压缩算法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20127180/