OscarRyz
OscarRyz

Reputation: 199284

Convert two booleans to an int

Probably this is extremely easy.

If I have two booleans, a and b, how can I get the equivalent "binary" number?

false and false = 0 
false and true  = 1 
true  and false = 2 
true  and true  = 3 

Upvotes: 4

Views: 975

Answers (4)

missingfaktor
missingfaktor

Reputation: 92076

Since you have marked this as language-agnostic, I'd post how to do this in Scala. :-)

scala> implicit def boolToAddable(a: Boolean) = new {
     |   def +(b: Boolean): Int = (a, b) match {
     |     case (false, false) => 0
     |     case (false, true)  => 1
     |     case (true,  false) => 2
     |     case (true,  true)  => 3
     |   }
     | }
boolToAddable: (a: Boolean)java.lang.Object{def +(b: Boolean): Int}

scala> false + false
res0: Int = 0

scala> false + true
res1: Int = 1

scala> true + false
res2: Int = 2

scala> true + true
res3: Int = 3

Alternatively you could use the trick suggested by @David above:

scala> implicit def boolToAddable(a: Boolean) = new {
     |   def +(b: Boolean) = (if(a) 2 else 0) + (if(b) 1 else 0)
     | }
boolToAddable: (a: Boolean)java.lang.Object{def +(b: Boolean): Int}

Upvotes: 3

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299108

Or a more general solution for an array of booleans:

public static BigInteger asBinary(boolean[] values){
    BigInteger sum = BigInteger.ZERO;
    for(int i = 0; i < values.length; i++){
        if(values[i]){
            sum = sum.add(
                BigInteger.valueOf(2).pow(values.length - (i+1)));
        }
    }
    return sum;
}

(See it work on ideone)

For efficiency reasons, it would probably be best to use ints for the internal processing if the array size is < 32, but this is just a demo, so I'll skip that.

Upvotes: 1

mikurski
mikurski

Reputation: 1363

This is more number theory than code; it's not an exact solution to your problem, but it might give you greater insight to what's going on.

A number in standard decimal notation (base 10) can be represented using a series of sums:

1023 is equivalent to 1*1000 + 0*100 + 2*10 + 3*1

This is equivalent to (1*10^3) + (0*10^2) + (2*10^1) + (3*10^0)

In the case of binary (base 2), a number like 101 can be represented as:

1*2^2 + 0*2^1 + 1*2^0 = 4+0+1 = decimal 5.

Upvotes: 0

3Dave
3Dave

Reputation: 29051

(left ? 2 : 0) + (right ? 1 : 0);

Not sure if java handles booleans like C, but if it does:

2*left+right;

Upvotes: 10

Related Questions