C - Bit Patterns Help
If i'm reading it right, he probably means to set the n-th bit to 1 in the variable.
An unsigned short is 16 bit wide , so you have bit 15 , bit 14 , bit 13 .... bit 1 , bit 0 so if you enter 3 , 13 , 8 that means you want the 4th bit from right set to 1 (because you start from bit 0), then you set the 14th bit from the right and so on.
You set and unset bits with the OR and XOR operators.. quoting quora.com article which quotes stackoverflow because i'm too lazy and don't have these memorized :
https://www.quora.com/How-do-you-set-clear-and-toggle-a-single-bit-in-C
QuoteSetting a bit
Use the bitwise OR operator (|) to set a bit.
number |= 1 << x;
That will set bit x.
Clearing a bit
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << x);
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
Toggling a bit
The XOR operator (^) can be used to toggle a bit.
number ^= 1 << x;
That will toggle bit x.
So for each number , make sure it's between 0 and 15 inclusive, then maybe clear that bit just in case it's already set, then set the bit to 1
If it's not obvious, the << shifts a variable to the left by the number of bits you specify ...
so "1" is 00000000 00000001 in binary and if you say 1 <<3 it becomes 00000000 00001000 and if you say number = number OR variable then that bit is set to 1 because 0 or 1 = 1 , 0 or 0 = 0 , 1 or 1 = 0.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now