So, I have an array of unsigned chars, currently I’m trying to write a Set method (changes the bit in given index to 1). The best way I could think to do this was instead of creating a mask for the whole array, I would just create a mask the size of a byte and only mask the index spot in the array with the given bit that the user wants to change. However, every way I try to do it, either nothing happens to the resulting array after OR’ing it with a mask of all 0’s with a 1 in the bit index, or I get a seg fault. The best I’ve been able to do is change the correct bit in the first array index. How my code is currently set up right now I understand why it’s only changing the correct bit in the first byte of the array, but every attempt to change this has failed, I don’t think this should be hard I just feel like I’m missing something, but pages of reading and google searches have lead me no where. Here’s a snipit of my code as of now…
void BitArray::Set (unsigned int index)
70 {
71 int spot; // index in barray where
72 // bit to be set is located
73 char mask;
74 if (index < 8)
75 {
76 spot = 0;
77 mask = 1 >> index - 1;
78 }
79 else
80 {
81 int spot = index / 8;
82 mask = 1 << (index - (8*spot) - 1);
83 }
84
85 *barray = *barray | mask;
86 }
Instead of the *barray = *barray | mask, I would intuitively want something like barray[spot] = barray[spot] | mask; to work. Any help is greatly appreciated.
I’m not sure why you’re going against your intuitive notion of
array[spot] = barray[spot] | mask;And you seem to be making the spot and mask calculations more complicated than necessary.Why did you make
index < 8a special case?In both cases
index / 8gives you the right byte index, correct?Second, how do either of the following lines give you the right bit position? Why are you shifting right at all? What does spot, the index of the byte you have to access, have to do with the bit position within the byte?
Here’s my untested solution: