I am working with some VB.NET code that seems to be casting a boolean value to an integer using CInt(myBoolean)
. The odd thing that is happening is that it returns -1 if the value is true. For example:
CInt(True) // returns -1 CInt(False) // returns 0
Is this common in other languages?
I thought that a boolean would be 1 if true and 0 if false. Also, is there a way to make Visual Basic assign 1 to true instead of assigning -1?
Using the method booleanObjectMethodToInt, we can convert a boolean value to an integer the same way we did with the static method.
Writing a Boolean Method Writing a method that returns a boolean is just like writing any method with a return value, but ultimately we are just returning either true or false. For example, suppose we are writing code for a hybrid-electric car.
If the Boolean value is true , the result is an int with a value of 1. If the scalar value is equal to 0, the Boolean value is 0; otherwise the Boolean value is 1.
To display Boolean type, firstly take two variables and declare them as boolean. val1 = true; Now, use if statement to check and display the Boolean true value. if(val1) System.
Typically, a value of false is represented by 0 and a value of true is represented by any non-0 integer value. The specific value for true and false (among others) are things that you shouldn't rely on - they can potentially be implementation specific. I'm not sure what you are trying to do, but it would probably be best to not rely on True
or False
having any specific integer values unless you absolutely have to.
The best explanation that I could find for VB's specific behavior comes from Wikipedia:
Boolean constant True has numeric value −1. This is because the Boolean data type is stored as a 16-bit signed integer. In this construct −1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value −1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[4] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time.
A work around for your initial use would be :
Dim i As Integer = CInt(Int(False))
This will return a 0.
Dim i As Integer = CInt(Int(True))
This will return a 1.
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