c++ - Setting Bit from Dynamic Array and Then Displaying it -
i have constructor creates bitarray object, asks user how many 'bits' use. uses unsigned chars store bytes needed hold many. wish create methods allow user 'set' bit, , display full set of bytes @ end. however, set method not seem changing bit, that, or print function (the overload) not seem printing actual bit(s). can point out problem please?
constructor
bitarray::bitarray(unsigned int n) { //now let's find minimum 'bits' needed n++; //if not "perfectly" fit //------------------------------------ehhhh if( (n % byte) != 0) arraysize =(n / byte); else arraysize = (n / byte) + 1; //now dynamically create array full byte size barray = new unsigned char[arraysize]; //now intialize bytes 0 for(int = 0; < arraysize; i++) { barray[i] = (int) 0; } }
set method:
void bitarray::set(unsigned int index) { //set indexed bit on barray[index/byte] |= 0x01 << (index%byte); }
print overload:
ostream &operator<<(ostream& os, const bitarray& a) { for(int = 0; < (a.length()*byte+1); i++) { int curnum = i/byte; char chartoprint = a.barray[curnum]; os << (chartoprint & 0x01); chartoprint >>= 1; } return os; }
for(int = 0; < (a.length()*byte+1); i++) { int curnum = i/byte; char chartoprint = a.barray[curnum]; os << (chartoprint & 0x01); chartoprint >>= 1; }
each time run loop, fetching new value chartoprint
. means operation chartoprint >>= 1;
useless, since modification not going carried out next time loop runs. therefore, print first bit of each char
of array.
Comments
Post a Comment