vb.net - 将 boolean 值转换为整数会返回 -1 表示 true?

标签 vb.net boolean

我正在与一些VB.NET合作代码似乎使用 CInt(myBoolean) 将 boolean 值转换为整数。发生的奇怪的事情是,如果值为 true,它会返回 -1。例如:

CInt(True)  // returns -1
CInt(False) // returns 0

这在其他语言中常见吗?

我认为 boolean 值如果为真则为 1,如果为假则为 0。另外,有没有办法让 Visual Basic 将 1 分配给 true 而不是分配 -1?

最佳答案

通常, false 值由 0 表示, true 值由任何非 0 整数值表示。 true 和 false(以及其他)的具体值是您不应该依赖的东西 - 它们可能是特定于实现的。我不确定您要做什么,但最好不要依赖 TrueFalse 具有任何特定的整数值,除非绝对必要。

我能找到的关于 VB 特定行为的最佳解释来自 Wikipedia :

Boolean constant True has numeric value −1. This is because the Boolean data type is stored as a 16-bit signed integer. In this construct −1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value −1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[4] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time.

关于vb.net - 将 boolean 值转换为整数会返回 -1 表示 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3621037/

相关文章:

vb.net - 我可以使用一种方法返回 SSRS 报告代码中的字符串列表作为 tablix 中的标题吗?

c - 使用哪个更安全? "==TRUE"或 "!= FALSE"

python - 为什么 bool 是 Python 3 中 int 的子类?

vb.net - 基本本地化(中性语言)

.net - VB stringbuilder 包含

.net - SEHException 未被 Try/Catch 捕获

asp.net - 更新面板错误 : Control with the ID "xxx" could not be found in the UpdatePanel

c++ - 我可以依赖一个新的 bool 被初始化为 false 吗?

java - toString 方法用 2D boolean 数组打印游戏板

c++ - 赋值运算符的 boolean 和字符串重载 (C++)