Saturday, November 04, 2006

將布林值轉成字串 BoolToStr

運用在邏輯運算的 Boolean 型態值有 true or false 兩個。因此, 這兩個字在 C++ 屬於 specific keywords。換句話說, 你不可以用這兩個字當變數名稱, 它們是有特定意義的。

我們再深入一點探討, 電腦是怎麼儲存這個形態的變數呢? 我們看看 BCB 中的 Help 是怎麼說的:
bool, true, false

Category

C++-Specific Keywords

Syntax
bool ;

Description
Use bool and the literals false and true to perform Boolean logic tests.

The bool keyword represents a type that can take only the value false or true. The keywords false and true are Boolean literals with predefined values. false is numericallly zero and true is numerically one. These Boolean literals are rvalues; you cannot make an assignment to them.

You can convert an rvalue that is of type bool to an rvalue that is int type. The numerical conversion sets false to zero and true becomes one.

You can convert arithmetic, enumeration, pointer, or pointer to member rvalue types to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false. Any other value is converted to true.

很顯然地, 這些 Boolean 值在電腦中, 也是用電腦基本的 0, 1 數值來儲存。"The keywords false and true are Boolean literals with predefined values. false is numericallly zero and true is numerically one." 此外, 我們也可以把一些其他型態的值轉換成布林值, 像 0, null pointer value, null member pointer value 會被轉換成 false, 其餘則是通通轉換成 true

在 BCB 中, 還提供了一個 BoolToStr 將布林值轉換成字串。
BoolToStr(bool B, bool UseBoolStrs)
Converts a Boolean value to an AnsiString.

Unit
SysUtils

Category
type conversion routines

extern PACKAGE AnsiString __fastcall BoolToStr(bool B, bool UseBoolStrs = false);

Description
BoolToStr converts the given Boolean value to a string as follows:

B UseBoolStrs  Returned string
true  false    "-1"
true  true    The first string in TrueBoolStrs (default, "TRUE");
false  false    "0"
false  true    The first string in FalseBoolStrs (default, "FALSE");

 

No comments:

Post a Comment