2013-11-21 35 views
0

我正在使用函數將字符序列壓縮爲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語句之後註釋掉所有的couts,並且取消之前的註釋,你會發現shift和bitused的值是正確的。然而,如果你沒有注意到「shift」值,那麼得到fffffffe的賦值,而不是-2(這可以通過在if語句下注釋掉couts來看出)。我覺得這個問題可能與輸出到流中有關,但我不確定。任何幫助將不勝感激!

+0

如果你知道你的整數不會小於0,那麼我建議你使用'unsigned char'。 –

回答

1

data的類型從char更改爲unsigned char。在某些情況下,data具有負值,因此當您將其投射到int以打印時,它將被填充爲1。

+0

糾正了我的問題,謝謝! –