How to Convert Boolean Values to Integers

Convert boolean to int in Java

int myInt = myBoolean ? 1 : 0;

^^

PS : true = 1 and false = 0

How to convert boolean value into int and vice versa in java?

C++ implicitly converts int to boolean. In Java, you will have to do that explicitly by yourself.
To convert an int to boolean, just check whether it's not zero like this: N != 0

So you have to modify your original expression to something like this:

if (((N & (N - 1)) != 0) || (N == 0))

Vice versa, to convert a boolean to an int, do something like this: int i = boolValue ? 1 : 0;

Convert boolean result into number/integer

Javascript has a ternary operator you could use:

var i = result ? 1 : 0;

Converting Boolean to Integer in Java without If-Statements

You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.

If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:

0x0000000002672580: sub    $0x18,%rsp
0x0000000002672587: mov %rbp,0x10(%rsp) ;*synchronization entry
0x000000000267258c: mov %edx,%eax
0x000000000267258e: add $0x10,%rsp
0x0000000002672592: pop %rbp
0x0000000002672593: test %eax,-0x2542599(%rip) # 0x0000000000130000
; {poll_return}
0x00000000025b2599: retq

Note: this is on hotspot server 7 - you might get different results on a different VM.

Converting Boolean value to Integer value in Swift

Swift 5

Bool -> Int

extension Bool {
var intValue: Int {
return self ? 1 : 0
}
}

Int -> Bool

extension Int {
var boolValue: Bool {
return self != 0
}
}

Can I manipulate Boolean values as ints in Java?

Is a boolean primitive in java a type in its own right?

Yes. boolean is a primitive type in its own right

can it be manipulated as an int?

No. It can not be implicitly or explicitly cast or otherwise used as an int (Java ain't C)

If you wanted to "coerce" it to an int:

boolean b;
int i = b ? 1 : 0; // or whatever int values you care to use for true/false

How do I convert boolean values to integers?

inflection_point = (firm.inflection_point ? 1 : 0)


Related Topics



Leave a reply



Submit