铸造一个布尔值,整数返回-1为真? [英] Casting a boolean to an integer returns -1 for true?

查看:378
本文介绍了铸造一个布尔值,整数返回-1为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟一些 VB.NET code,这似乎是铸造一个布尔值工作使用 CINT(myBoolean的整数)。正在发生奇怪的是,它返回-1,如果值是true。例如:

I am working with some VB.NET code that seems to be casting a boolean value to an integer using CInt(myBoolean). The odd thing that is happening is that it returns -1 if the value is true. For example:

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

这是常见于其他语言?

Is this common in other languages?

我认为,一个布尔是1,如果真和0,如果假的。此外,有没有一种方法,使Visual Basic中指定1到真实的而不是分配-1?

I thought that a boolean would be 1 if true and 0 if false. Also, is there a way to make Visual Basic assign 1 to true instead of assigning -1?

推荐答案

通常情况下,值false将重新由0 psented $ P $和任何非0整数值psented真正重新$ P $的值。他们有可能成为具体执行 - 对于您不应该依赖真假(其中包括)是具体事物的价值。我不知道你正在尝试做的,但它很可能是最好不要依赖于有任何具体的整数值,除非你绝对必须的。

Typically, a value of false is represented by 0 and a value of true is represented by any non-0 integer value. The specific value for true and false (among others) are things that you shouldn't rely on - they can potentially be implementation specific. I'm not sure what you are trying to do, but it would probably be best to not rely on True or False having any specific integer values unless you absolutely have to.

这是我能找到的VB的具体行为的最好解释来自维基百科

The best explanation that I could find for VB's specific behavior comes from Wikipedia:

布尔常量真有数字值-1。这是因为,布尔数据类型被存储为一个16位带符号整数。在这种结构-1计算结果为16个1(布尔值True),0 16 0(布尔值false)。在16位有符号整型值0,这将返回整数值-1,换句话说真=不假执行不操作时,这是显而易见的。上一个整数的各个位,如与,或,XOR和不执行逻辑运算时,这种固有的功能变得特别有用。[4]真正的定义也与70年代初期以来微软基本实现基本一致,也与到的CPU指令的时候的特性。

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.

这篇关于铸造一个布尔值,整数返回-1为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆