Advanced question

I have the following struct:

1
2
3
4
5
struct bitFields
{
unsigned short userInputA : 3; 
unsigned short userInputB : 3;
};


The variables above only store values between 1 and 7 (including 1 and 7). My program asks the user to enter a number between 1 and 7. Upon entering a valid number, I execute a certain function based on the user's input and I reset the bits of the variables above back to 0 for future use. Very simple.

BUT, a problem occur when the user enters a value like 9. Apparently, 9 is being interpreted as 1. Many problems occur whenever the user enters a rubbish value like 589035 etc. My program goes haywire. I understand that the bits are possibly wrapping around. So how can I fix this problem please?
Last edited on
 
user_input = user_input < 1 ? 1 : user_input > 7 ? 7 : user_input;
Hello helios,

If it's not too much to ask, could you please give me an example as to how I go about applying this formula? Isn't this the same as saying

1
2
3
4
5
6
7
8
if (bitFieldsObj.userInputA < 1)
{
bitFieldsObj.userInputA = 1;
}
else if (bitFieldsObj.userInputA > 7)
{
bitFieldsObj.userInputA = 7;
} 



Isn't there a way I can make the variable only read the last 3 bits?
Last edited on
Yes, it's saturation logic. Write it however you prefer.
That didn't fix it, the compiler is still interpreting 9 as 1 and executing the function associated with the value 1. This is giving me a headache :/
I just noticed. You should saturate the input before assigning its value to the bitfield. That's why my snippet says user_input. Obviously a 3-bit value can't possibly be greater than 7.
Topic archived. No new replies allowed.