2013-04-01 44 views
-1

我正在處理壓縮和解壓縮的任務。更具體地說,遊程長度編碼(9位塊)的變化。我遇到的問題涉及「類型」位的符號。我能夠獲得所需的位,但是,在位應該是1的情況下,我的printf返回-1。這會讓我相信我在我的位移中沒有做正確的事情,但我並不知道可能會發生什麼。位移導致負數

void bitShift(char * mostFreq, unsigned char * byteBuf, int byteCount) { 
    char type; 
    int typels = 0; 
    int typers = 7; 

    int i = 0; 
    for(i = 0; i < byteCount - 1; i++) { 
      type = byteBuf[i]; 
      printf("type before = %d\t", (unsigned int)type); 
      type = type << typels; 
      type = type >> typers; 
      typels++; 
      printf("type after = %d\n", (unsigned int)type); 
    }/*End for i*/ 


    for(i = 0; i < byteCount; i++) 
      byteBuf[i] = 0; 

}/*End bitShift*/ 

void decompressFile(char * mostFreq) { 
    unsigned char byteBuf[9] = { 0 }; 
    int num, byteCount, i; 
    num = 0; byteCount = 0; i = 0; 
    unsigned char buf; 
    while((num = read(0,&buf, 1)) > 0) { 
      byteBuf[byteCount] = buf; 
      byteCount++; 
      if(byteCount == 9) {/*Flush bytes if buffer is full*/ 
        bitShift(mostFreq, byteBuf, byteCount); 
        for(i = 0; i < 9; i++) { 
          byteBuf[i] = 0; 
        }/*End for i*/ 
        byteCount = 0; 
      }/*End if*/ 
    }/*End while*/ 
    if(num == 0) {/*If EOF*/ 
      if(byteCount != 0) {/*Bits have not been flushed*/ 
        bitShift(mostFreq, byteBuf, byteCount); 
      }/*End if*/ 
    } else if(num < 0) { 
      perror("Read error"); 
      exit(1); 
    }/*End else if*/ 

}/*End decompressFile*/ 
+0

爲什麼'char type;'在'bitShift'中而不是'unsigned char type';'無處不在? – rodrigo

+0

這是問題。我以某種方式跳過那一個。謝謝 – kubiej21

回答

4

您的問題是,你聲明type爲純char,在您的系統似乎是一個符號的類型。

所以,當你有例如0x80,它實際上是-128,負號,當它被右移符號位擴展:1位:0xC0 (-64),2位:0xE0 (-32),... 7位:0xFF (-1)

將其更改爲unsigned char並完成!