Question

I'm having some trouble getting started with a lab of mine. The lab has the following instructions:

Given a value int input = 0b10010110 determine what sports an individual likes. Assume there will be no errors in this input. From left to right, each position represents the following: Football, Baseball, Volleyball, Swimming, Softball, Soccer, Hockey, Lacrosse.

If there is a 1 is in that position, then the person likes that sport. Based on the “binary” input given, output to the screen all of the sports that the user enjoys. For the given binary number, the user likes, football, swimming, soccer and hockey.

  • Do not make an array of characters.

  • Be sure to use an enumerated data type.

I'm not sure how I can compare each position of the string to tell whether it is a 1 or 0. One idea I have is to use an enumerated type where I set each sport to a ten digit number where only its appropriate position is 1

enum sport{
    Football = 0010000000,
    Baseball = 0001000000,
    Volleyball = 0000100000, 
    ... , 
    Lacrosse = 0000000001
};

I would then shift left/ right on the given value "input" the appropriate amount of times to leave only the specified position with its original value and to set all other values to 0. For Football:

input << 2; input >> 9; input << 7;

So the new set value would be 0010000000. Then I'd be able to compare the number as a whole. I would have to that for each case, but I cannot think of a different way to do it.

Am I completely off? Is there a more functional way to check the value of each position using bit operations? Thanks for any assistance in advance.

Was it helpful?

Solution

Use bitwise AND operator &:

if (input & Football) {
    // Football bit is set
} else {
    // Football bit is not set
}

Also note that the 0b prefix is a compiler extension but is not standard C. And in your enum values, a number starting with the 0 prefix is in octal format (you have to fix this). I suggest you to use hexadecimal format for bit manipulation.

OTHER TIPS

You could make things a bit more readable if you define you sport values by shifting a 1 to the left by the appropriate number of places; in fact, you could use a simple enumeration for the sport values, and use that to specify how many places to shift the bit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top