![]() If this bit is one, then the expression returns a non-zero value, which is true, which then returns one from the ternary. The real comparison, therefore, only takes place on one bit, somevar.bit. The zeroes elsewhere mean that the & on those bits will always evaluate to zero. The_bit = (( some_var & (1 << (n-1) ) ) ? 1 : 0 ) Ī slightly more generalized look at the whole ternary statement now:įirst we create a mask with a 1 in the place of the bit we want to find and zeroes elsewhere. This means that the statement evaluates to 1. In our example, we get an expression that looks likeįour is non-zero, so it evaluates to true. It then procedes to evaluate whatever follows the colon. If it is false, then it ignores code until it reaches a. ![]() If the expression is true, the expression following the operator is evaluated. Time for a quick lesson in ternary! The ternary operator ? looks at the expression that precedes it. Now, we plug this value (4) back into our ternary expression. So, what we are really looking at in the example is Any place where both digits are 1 evaluate to 1. It checks each bit place in each string against each other. Now you see that we compare the mask (1 << (n-1) ) with the variable to be tested using the binary bitwise and operator (&). The_bit = (( some_var & (1 00000100 (assuming an 8 bit int, didn’t check how large an int on the PIC is, but it doesn’t matter for the point of this demonstration) An expression like this is known as a mask, and can be used with the & operator to test a single bit. Int n=3 /* the position of the bit we want */ ![]() ![]() Int some_var=5 /* the variable we will be extracting a bit from. Since I didn’t know how to do this, I thought some people might want to know. ![]()
0 Comments
Leave a Reply. |