& and ? used in code

Hi all,

I have read the reference library to try and understand this but they seem to be used in different context i though & was a bitwise and but in this case i dont understand what it means

return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1

because i know what the code is trying to do i get what its doing but if it was used somewhere else wouldnt have an idea.

This code is from the wii nunchuck code. Its basically saying if the byte it 0 use 0 if 1 use 1.

Anyone know what these & and especialy the ? actually mean and where they can be used,

& is bitwise AND. Why do you think it doesn't apply in this situation?

? is the ternary operator (or tertiary) - if the condition to the left of the ? evaluatues true, the value of the expression to the left of the colon is returned, else the value of the expression to the right of the colon is returned.

return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1

says "take the sixth element of nunchuck_buf and shift it right one place. Mask off the least-significant bit and test the resulting value. If the bit is 1, return 0, otherwise return 1"

Oh k thanks you seem to understand that very well. so in this case the & is "and test" as part of the return expression. I understand the ? now but how does & become test or is it after ) with a return expression it is test. i would have thought doing this for the first time it would be bug[5] >>1) == 1)....

return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1

The parentheses give the order of evaluation: (nunchuck_buf[5] >> 1) evaluates first. ((nunchuck_buf[5] >> 1) & 1) is next then the value of that expression is tested true/false (non-zero == true / zero == false)

You could write it out:

byte bit = nunchuck_buf[5] >> 1;
bit = bit & 1;
if (bit == 1)
  return 0;
  return 1;

Thanks all perfectly understood, i was thinking that after ) it put it in a test state but it is simply doing the bitwise and.

Iv used vb code for a bit with excel and think it has a preset order like if(evalution, if true, if false) sort of thing, but im clear now thanks all