Casting a boolean to an integer returns -1 for true?

Viewed 51368

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?

11 Answers

I had the same problem and used Math.Abs function on the result :)

I found the other answers lacking for the specific VBA scenario I was working with. This is not tested in VB.NET.

I wanted to take any given number that was <> 0 and make it 1, and keep 0 as 0 in a single line of code, without an If statement. The way that I ended up doing this, which I did not see in other given answers, was:

Abs(CBool(iCount))

CBool() converts the given number (iCount in example above) to Boolean, narrowing the possible results to two values; True with a value of -1 and False with a value of 0.

Abs() then takes the absolute value (no negatives) of the Boolean to return 0 for False and 1 for True.

In practice, the following return 0:

Abs(CBool(0))
Abs(False)

And the following return 1:

Abs(CBool(1))
Abs(CBool(-1))
Abs(CBool(-38473))
Abs(CBool(358677))
Abs(True)

I hope that this is useful for anyone else playing with specific scenarios such as this.

I may be a bit late but here's a simple workaround to receive the typical 1 for True and 0 for False.

Multiply the boolean with -1 like so:

CInt(True) * -1
CInt(False) * -1

Which then returns

1
0

Related