2013-04-05 23 views
0

我有一個構造函數,它創建一個BitArray對象,它向用戶詢問他們想要使用多少'位'。然後它使用無符號字符來存儲需要保存多個字節的字節。然後我希望創建允許用戶「設置」某個位的方法,並且還要在最後顯示全部字節集。但是,我的Set方法似乎並沒有改變這個位,或者我的Print函數(Overload)似乎實際上並沒有打印實際的位。請問有人能指出問題嗎?從動態數組中設置位,然後顯示它

構造

BitArray::BitArray(unsigned int n) 
{ 

//Now let's find the minimum 'bits' needed 

n++; 
//If it does not "perfectly" fit 
//------------------------------------ehhhh 
if((n % BYTE) != 0) 
    arraySize =(n/BYTE); 
else 
    arraySize = (n/BYTE) + 1; 

//Now dynamically create the array with full byte size 
barray = new unsigned char[arraySize]; 

//Now intialize bytes to 0 
for(int i = 0; i < arraySize; i++) 
{ 
    barray[i] = (int) 0; 
} 

} 

設置方法:

void BitArray::Set(unsigned int index) 
{ 
     //Set the Indexed Bit to ON 
     barray[index/BYTE] |= 0x01 << (index%BYTE); 
} 

打印過載:

ostream &operator<<(ostream& os, const BitArray& a) 
{ 
     for(int i = 0; i < (a.Length()*BYTE+1); i++) 
     { 
      int curNum = i/BYTE; 
      char charToPrint = a.barray[curNum]; 
      os << (charToPrint & 0X01); 
      charToPrint >>= 1; 
     } 
    return os; 
} 
+0

也許我很困惑..但它看起來像你正在使用'char []'數組來保存每個索引中的單個'位'值。如果是這樣的話,你的'Set'函數應該只是:'barray [index - 1] ='1';'?如果陣列中的每個char都保持1或0,則不需要移位。 – 2013-04-05 01:27:14

回答

0
for(int i = 0; i < (a.Length()*BYTE+1); i++) 
    { 
     int curNum = i/BYTE; 
     char charToPrint = a.barray[curNum]; 
     os << (charToPrint & 0X01); 
     charToPrint >>= 1; 
    } 

每次運行循環時,你獲取的charToPrint新值。這意味着操作charToPrint >>= 1;是無用的,因爲該修改不會在下一次循環運行時執行。因此,您將始終僅打印陣列中每個char的第一位。

+0

謝謝,親切的先生。 – JcKelley 2013-04-05 03:36:23

相關問題