15,882,329 members
1.00/5 (1 vote)
See more:
can you please explain this code

JavaScript
`var demo = (y1 & 1) ? x1 + 0.5 : x1;`

or convert it to python because i know python

thank you
Posted
Kornfeld Eliyahu Peter 3-Nov-14 7:49am
It is hard to believe that python version will help you anyway - but...
demo = (y1 & 1) if x1 + 0.5 else x1
Member 11202368 3-Nov-14 19:56pm
thanks for reply, i want to use this code in python but i have no idea about js

## Solution 1

why not read some documentation and try to understand it?
Conditional (Ternary) Operator (?: ) [^]
JavaScript Operators[^]

Sergey Alexandrovich Kryukov 3-Nov-14 11:15am
Fully agree, a 5.
However, I decided to answer in detail, but only to compensate for confusing Solution 2, which is incorrect.
—SA
DamithSL 3-Nov-14 11:51am
Thank you, SA
Manas Bhardwaj 3-Nov-14 11:41am
Yes +5!
DamithSL 3-Nov-14 11:51am
Thank you, Manas
Maciej Los 3-Nov-14 11:52am
+5!

## Solution 3

Solution 2 is not quite correct.

The corrected pseudo-code is:
C#
```if (first bit (#0) in y1 is set)
{ // if this bit is set:
demo = x1 + 0.5;
}
else
{ // if this bit is clear:
demo = x1;
}```

The bit check is done by the bitwise AND operator '&': test number `y1` is compared with a bit mask with a single bit installed (1, 2, 4, 8, etc.) and the result is either 0 or not.
Now, the trick is: if the operand of "`if`" is a number, it behaves as False if the number is 0, True in all other cases; this is a dirty C-like convention.

—SA

v4
DamithSL 3-Nov-14 11:29am
5wd, Very nicely explained
Sergey Alexandrovich Kryukov 3-Nov-14 12:25pm
Thank you, Damith,
—SA
Manas Bhardwaj 3-Nov-14 11:41am
Thanks for your comment on my solution. Yes, I overlooked that.

+5!
Sergey Alexandrovich Kryukov 3-Nov-14 12:25pm
Thank you Manas.
—SA
Maciej Los 3-Nov-14 11:53am
+5!

## Solution 2

I am not sure if this is really Python or JavaScript related. And as you proclaimed your Python (or any other programming language), it should have been understandable.

Anyway, here is the pseudo-code:

JavaScript
```if (y1 & 1) is true
{
demo = x1 + 0.5;
}
else
{
demo = x1;
}```

v2
Sergey Alexandrovich Kryukov 3-Nov-14 11:14am
Sorry, Manas. This is incorrect. The expression in the brackets checks up if the 1st bit of y1 is set.
—SA
Member 11202368 3-Nov-14 20:15pm
thank you