Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
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
Comments
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

why not read some documentation and try to understand it?
Conditional (Ternary) Operator (?: ) [^]
JavaScript Operators[^]
 
Share this answer
 
Comments
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.
Please see Solution 3.
—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 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.

Please see, for example, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators[^].

—SA
 
Share this answer
 
v4
Comments
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!
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;
}
 
Share this answer
 
v2
Comments
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.
Please see Solution 3.
—SA
Member 11202368 3-Nov-14 20:15pm    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900