Go Down

### Topic: & and ? used in code (Read 858 times)previous topic - next topic

#### Dan_68

##### Aug 20, 2011, 10:56 am
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,

#### AWOL

#1
##### Aug 20, 2011, 11:26 amLast Edit: Aug 20, 2011, 11:29 am by AWOL Reason: 1
& 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.

Code: [Select]
`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"
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

#### Dan_68

#2
##### Aug 20, 2011, 11:35 am
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)....

#### AWOL

#3
##### Aug 20, 2011, 11:49 am
Code: [Select]
`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:
Code: [Select]
`byte bit = nunchuck_buf[5] >> 1;bit = bit & 1;if (bit == 1)  return 0;else  return 1; `
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

#### Dan_68

#4
##### Aug 20, 2011, 11:56 am
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

Go Up