Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean to integer conversion

I have 3 separate Boolean variables, bit1, bit2 & bit3 and I need to calculate the decimal integer equivalent in JavaScript?

like image 459
user1661099 Avatar asked Sep 10 '12 19:09

user1661099


People also ask

Can you cast a boolean to an int in Java?

Using the method booleanObjectMethodToInt, we can convert a boolean value to an integer the same way we did with the static method.

How do you convert a boolean to an integer in Python?

To convert boolean to integer in python, we will use int(bool) and then it will be converted to integer.

Can you compare a boolean to integer?

The compare() method of Java Boolean class compares the two Boolean values (x and y) and returns an integer value based on the result of this method.


2 Answers

+true //=> 1 +false //=> 0  +!true //=> 0 +!false //=> 1 
like image 64
yckart Avatar answered Oct 11 '22 16:10

yckart


Ternary operator is a quick one line solution:

var intVal = bit1 ? 1 : 0; 

If you're unfamiliar with the ternary operator, it takes the form

<boolean> ? <result if true> : <result if false> 

From Sime Vidas in the comments,

var intVal = +bit1; 

works just as well and is faster.

like image 32
Samuel Avatar answered Oct 11 '22 17:10

Samuel