reading a set of bits with a boolean operator, I think

For part of an assignment that I'm working on for class, I need to write a for() loop that will read a series of bits individually and assign values of true or false to them. For example, I need my program to be able to read 1011001 and determine that there are four trues and three falses and keep track of that fact. I then need the program to subtract one of those values from the total, so that if there are seven trues there will be six or if there are four trues and three falses there will be four trues and two falses.

I think I might need to use a .get statement but I'm not entirely sure.

Also, if you happen to write some example code, please make sure to write the code as though "using namespace std;" is already part of the program. I have a hard time reading the code otherwise. All of those colons and "std"'s make it hard for me to understand what is being written. Please, also, explain what the code is trying to accomplish.

Thank you for the help ahead of time.

closed account (48T7M4Gy)
Your turn again Ike. We haven't got a clue how to do this either. Tell the prof to give you easier stuff next time like int main(){} life's too short.
To check if a bit is on you can use bitwise AND.
1
2
3
unsigned char byte = 170; // 10101010
bool firstBitOn = byte & 1; // 10101010 AND 00000001 == 00000000 -> false
bool sixthBitOn = byte & 1 << 5; // 10101010 AND 00100000 == 00100000 -> true 

Use a loop to check every bit.
It relies on the fact that any value different from 0 means true. So when the AND returns true you can increment a counter for the bits that are on.

I don't know if there's a better way to do this though.
Topic archived. No new replies allowed.