Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why delphi BoolToStr true is represented as -1

Delphi function BoolToStr converts boolean value to a string.

The result is either true or false, or 'numeric', '-1' and '0' respectively. Why -1 and not 1?

like image 922
Doege Avatar asked Feb 12 '19 09:02

Doege


2 Answers

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
like image 189
David Heffernan Avatar answered Oct 04 '22 22:10

David Heffernan


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.

like image 26
GolezTrol Avatar answered Oct 04 '22 20:10

GolezTrol