Is there a builtin way to cast bools to integers or vice versa? I've tried normal casting, but since they use different underlying types, conversion isn't possible the classic way. I've poured over some of the specification, and I haven't found an answer yet.
You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.
Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.
Using a bool IMO reflects its use much better than using an int . In fact, before C++ and C99, C89 didn't have a Boolean type. Programmers would often typedef int Bool in order to make it clear that they were using a boolean.
Int to bool is easy, just x != 0
will do the trick. To go the other way, since Go doesn't support a ternary operator, you'd have to do:
var x int if b { x = 1 } else { x = 0 }
You could of course put this in a function:
func Btoi(b bool) int { if b { return 1 } return 0 }
There are so many possible boolean interpretations of integers, none of them necessarily natural, that it sort of makes sense to have to say what you mean.
In my experience (YMMV), you don't have to do this often if you're writing good code. It's appealing sometimes to be able to write a mathematical expression based on a boolean, but your maintainers will thank you for avoiding it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With