49

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

Himanshu
  • 31,810
  • 31
  • 111
  • 133
user1661099
  • 591
  • 1
  • 4
  • 3
  • 4
    are you looking to convert each to a number or the combination into what amounts to a 3 bit set where i.e. bit3 would represent 4? – Matt Whipple Sep 10 '12 at 19:59
  • 1
    possible duplicate of [Convert boolean result into number/integer](http://stackoverflow.com/questions/7820683/convert-boolean-result-into-number-integer) – James Lawruk Aug 27 '14 at 17:33
  • Possible duplicate: https://stackoverflow.com/questions/7820683/convert-boolean-result-into-number-integer – cs95 Feb 19 '20 at 00:56

9 Answers9

87
+true //=> 1
+false //=> 0

+!true //=> 0
+!false //=> 1
yckart
  • 32,460
  • 9
  • 122
  • 129
  • 8
    I like concise answers but i'd appreciate if you could shortly explain it – Doug Sep 07 '18 at 15:16
  • Here's a link to the documentation for examples and explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_() –  Jun 12 '19 at 22:12
  • @Doug Thanks to [@parsonsbots](https://stackoverflow.com/questions/12358554/boolean-to-integer-conversion/19842255#comment99720871_19842255) half the way should be explained. Here's the rest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT_(!) – yckart Jul 08 '19 at 09:16
  • it is bad solution. try +undefined – Jiraff537 Oct 16 '19 at 10:28
  • 1
    @Jiraff537 - `undefined` is not a boolean value. – Ted Hopp Dec 03 '21 at 13:50
33

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.

Samuel
  • 16,923
  • 6
  • 62
  • 75
  • Won't just `var intVal = bit1` do the trick? A boolean is after all either 1 or 0, so that assigns 1 or 0 automatically. – SexyBeast Sep 10 '12 at 20:00
  • @Cupidvogel There is no such thing as a implicit conversion during assignment, and JavaScript has a separate boolean type (try `typeof true`, and refer to `Boolean`). So how would this do the trick? –  Sep 10 '12 at 20:02
  • 7
    Number conversion can be done with the `+` unary operator: `var intVal = +bit1;`. No need for the ternary here. – Šime Vidas Sep 10 '12 at 20:02
  • Dunno, just do something like `a = 5 > 44; alert(a+456.5);`, you will see `456.5`. Change 44 to 4, you will see `457.5`. – SexyBeast Sep 10 '12 at 20:04
  • @Cupidvogel, the only issue is if you don't do any numeric operations on the boolean value, it won't be converted to a numeric type. – Samuel Sep 10 '12 at 20:05
  • @Cupidvogel That's because the booleans are converted to 0/1 if you do arithmetic with them. That doesn't mean they're interchangeable in other contexts (e.g., output). –  Sep 10 '12 at 20:05
  • If I don't do numeric operations on it, then why would I need to seek its decimal value? – SexyBeast Sep 10 '12 at 20:06
  • @ŠimeVidas Thanks, I added your solution – Samuel Sep 10 '12 at 20:06
  • @delnan, that is precisely the problem, I have been using var intVal = bit1 and it throws up random errors. what isthe format of the typeof true statement? – user1661099 Sep 10 '12 at 20:07
  • @Cupidvogel display in UI. If you concat bit1 with a string it will output "true" or "false". That's just one example – Samuel Sep 10 '12 at 20:08
  • @user1661099 *What* errors? As for `typeof true` is just tells you the type of `true` is "boolean", which shows that booleans are separate from numbers. –  Sep 10 '12 at 20:09
  • Your second example should look like ` ? : `. You have your operators reversed. – Alex Aug 11 '15 at 13:56
  • Ternary operator is perfect for me! I'm passing a `boolean` value to a function that writes the value to a database. But the DB is MySQL, so the `boolean` needs to be converted to a `tinyint`. Using your answer I can now do it as short and non-intrusive as possible like this (regular if-clause causes error): `writeToDb($("#checkbox").prop("checked")?1:0); //call to function` – myfunkyside May 23 '16 at 23:25
20
Number(true) // => 1
Number(false) // => 0
Tim
  • 2,805
  • 25
  • 21
13

If what you're asking is how to get the 3-bit integer value based on bit1 (MSB), bit2, and bit3 (LSB), you can just do the following:

var intval = bit1 << 2 | bit2 << 1 | bit3;

The left shifts (<<) will automatically convert the booleans to their corresponding int values.

Live demo: http://jsfiddle.net/DkYqQ/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
7

Use ~~ :

bit1 = ~~bit1; // bit1 = true will return 1 or bit1 = false rtuen 0
bit2 = ~~bit2;
bit3 = ~~bit3;

sum = bit1 + bit2 + bit3;
Otman Bouchari
  • 196
  • 1
  • 6
3
function boolToInt(bool){ return bool ? 1 : 0 }
function boolToInt(bool){ return bool | 0 }
function boolToInt(bool){ return bool & 1 }
function boolToInt(bool){ return ~~bool }
function boolToInt(bool){ return +bool }

choose!

MypKOT-1992
  • 191
  • 3
  • Can you explain what you did here? – M. Adeel Khalid Feb 26 '17 at 04:51
  • **1.** analog: `if (bool == true) { return 1 } else { return 0 }` **2,3,4.** automatically leads boolean to integer before bitwise operations **2.** bitwise or: `true | 0` => 1; `false | 0` => 0 **3.** bitwise and: `true &1` => 1; `false & 1` => 0 **4.** bitwise not, double-inverted: `~true` => -2; `~ -2` => 1; `~false` => -1; `~ -1` => 0; **5.** analog `null + true`, `null + false`, where automatically leads boolean to integer and null to 0; if to use function as is and bool === undefined functions 1-4 return 0; function 5 return NaN; – MypKOT-1992 Feb 26 '17 at 06:44
  • function boolToInt(bool){ return +bool } // what if **bool = undefined** – Jiraff537 Oct 16 '19 at 10:30
  • comment above - "...bool === undefined functions 1-4 return 0; function 5 return NaN" – MypKOT-1992 Oct 19 '19 at 13:23
1

You have the option of using ternary operator, It will look something like this:

var i = result ? 1 : 0;
C_sharp
  • 408
  • 5
  • 26
  • Also you can use, int myInt = (bit1)?1:0 ; – C_sharp Sep 10 '12 at 20:03
  • 1
    No, you can't use `int` in place of `var`, and while you can omit the whitespace, you shouldn't and it does not qualify as a different approach. –  Sep 10 '12 at 20:05
0

Well, this could be two things. Do you want the bitwise decimal equivalent, as if you'd squished bit1, bit2 and bit3 together in adjacent significant bits? Or do you want the hamming weight, where you count how many bits are set?

If you want the bitwise equivalent, basically you want to use a combination of bit-shifting and OR-summing, which is pretty common. In pseudocode:

var intResult = 0;
for each bit in {bit1, bit2, bit3}
{
   int bitVal = 0;
   if(bit) bitVal = 1;
   intResult = (intResult << 1) | bitVal;
}

If you want the hamming weight, then simply increment the result for each bit that is set:

var intResult = 0;
for each bit in {bit1, bit2, bit3}
   if(bit) intResult++;

If your language allows the use of booleans as integer values (true = 1, false = 0) these get easier:

//bit-concatenation
var intResult = 0;
for each bit in {bit1, bit2, bit3}
   intResult = (intResult << 1) | bit;

//hamming weight
var intResult = 0;
for each bit in {bit1, bit2, bit3}
   intResult += bit;
KeithS
  • 70,210
  • 21
  • 112
  • 164
0
function boolsToInt(){
  var s = "";
  for(var i in arguments)s+=arguments[i]?1:0;
  return parseInt(s,2);
}

input can represented as bool or int:

console.log(boolsToInt(true,false,true,true));
console.log(boolsToInt(1,0,1,1));