Why delphi BoolToStr true is represented as -1
A possible explanation is that a boolean is typically not stored in a single bit, but in an integer. If you do a bitwise not
of an integer 0 (binary 0000 0000 ...), it will be binary 1111 1111 ....), which means -1 for two complements signed integers.
So if you say, false := 0; true := not false;
, it makes sense that true is -1.
In the various BASIC dialect, true is also -1 for the same reason.
The source of these particular values is surely down to the 0
and -1
being the values used by the COM boolean type.
Certainly in older versions of the Delphi RTL this function was used when converting variants from one type to another, so I'd be reasonable confident that COM variant support was the reason behind this decision.
You can see the remnants of that original code today in VariantChangeSimpleIntoSimple
found in System.VarUtils
. When asked to convert varBoolean
to varOleStr
it does:
VarOleStrFromStr(Dest, BoolToStr(LSource.VBoolean))
Further reading:
- BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool.
- Not Logical Is VBScript