我正在与一些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(以及其他)的具体值是您不应该依赖的东西 - 它们可能是特定于实现的。我不确定您要做什么,但最好不要依赖 True
或 False
具有任何特定的整数值,除非绝对必要。
我能找到的关于 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/