Having problem with function to set bits

I'm working on an assignment where I have to implement a class called BitArray which has functions that perform bitwise operations. I'm working on the Set() function, which takes in an unsigned int value and set the corresponding bit to 1. I'm very new to all this, especially bit masking. The problem is logical, as I'm able to set the first bit, the one furthest to the left, but no others.

The set function is supposed to set the bit at index to 1. I figured I first need to determine which byte the bit is in, and then how many times I need to shift the mask and OR it with the bit.

I can't see what the problem is, so any insight as to what I did wrong would be great! Thanks.

Last edited on
Could really use some help on this
> static const int CHAR_SIZE = sizeof(unsigned char);

In C++, by definition, sizeof(char), sizeof(unsigned char) and sizeof(signed char) is 1.

To find the number of bits in an unsigned char:
1
2
#include <limits>
const int charBits = std::numeric_limits<unsigned char>::digits ;




1
2
3
4
5
// determine which byte go to go 
int byteIndex = index / charBits ; 

// determine how many times to shift 
int shift = charBits - index%charBits - 1 ;
Last edited on
Would
1
2
#include <limits>
const int charBits = std::numeric_limits<unsigned char>::digits ;

produce a number of bits other than 8? I was told to use the sizeof(char)*8
to determine the number of bits in a char for this assignment.

Bits are only being set when I pass in a multiple of 8 to Set(). For instance, calling Set(8) sets the first bit, Set(16) sets the second bit, Set(24) sets the third and so on. Is that because of what shift is set to now?
Last edited on
> Would
>
1
2
#include <limits>
const int charBits = std::numeric_limits<unsigned char>::digits ;

> produce a number of bits other than 8?

It is implementation dependent. It wpuld be 8 on implementations where a byte is an octect.


> I was told to use the sizeof(char)*8 to determine the number of bits in a char

You might as well hard code a magic number 8. ( sizeof(char)*8) == 1 * 8


> Bits are only being set when I pass in a multiple of 8 to Set().

Repeat:
1
2
3
4
5
// determine which byte go to go 
int byteIndex = index / charBits ; 

// determine how many times to shift 
int shift = charBits - index%charBits - 1 ;
Got everything working, thanks for the help JLBorges!
Topic archived. No new replies allowed.