I was wondering why True is equal to -1 and not 1. If I remember correctly (back in the days) in C, “true” would be equal to 1.
Dim t, f As Integer
t = True
f = False
Console.WriteLine(t) ' -1
Console.WriteLine(f) ' 0
Console.ReadLine()
When you cast any non-zero number to a
Boolean, it will evaluate toTrue. For instance:However, as you point out, any time you cast a
Booleanthat is set toTrueto anInteger, it will evaluate to -1, for instance:The reason for this is because
-1is the signed-integer value where all of its bits are equal to 1. Since aBooleanis stored as a 16-bit integer, it is easier to toggle between true and false states by simply NOT’ing all of the bits rather than only NOT’ing the least significant of the bits. In other words, in order forTrueto be1, it would have to be stored like this:But it’s easier to just store it like this:
The reason it’s easier is because, at the low-level:
Whereas:
For instance, you can replicate this behavior using
Int16variables like this:This would be more obvious if you were using unsigned integers, because then, the value of
Trueis the maximum value rather than -1. For instance:So, the real question, then, is why in the world does VB.NET use 16 bits to store a single bit value. The real reason is speed. Yes, it uses 16 times the amount of memory, but a processor can do 16-bit boolean operations a lot faster than it can do single-bit boolean operations.
Side note: The reason why the
Int16value of-1is stored as1111111111111111instead of as1000000000000001, as you might expect (where the first bit would be the “sign bit”, and the rest would be the value), is because it is stored as the two’s-complement. Storing negative numbers as the two’s-complement means that arithmetic operations are much easier for the processor to perform. It’s also safer because, with two’s-compliment, there’s no way to represent0as a negative number, which could cause all sorts of confusion and bugs.