将布尔值转换为整数返回 -1 为真? [英] Casting a boolean to an integer returns -1 for true?

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

问题描述

我正在处理一些似乎正在转换布尔值的 VB.NET 代码使用 CInt(myBoolean) 将值转换为整数.发生的奇怪事情是,如果值为真,它返回 -1.例如:

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 分配给 true 而不是分配 -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 表示,true 值由任何非 0 整数值表示.true 和 false (以及其他)的特定值是您不应该依赖的东西 - 它们可能是特定于实现的.我不确定您要做什么,但最好不要依赖 TrueFalse 具有任何特定整数值,除非您绝对必须这样做.

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:

布尔常量 True 具有数值 -1.这是因为布尔数据类型存储为 16 位有符号整数.在此构造中,-1 计算为 16 个二进制 1(布尔值 True),0 计算为 16 个 0(布尔值 False).这在对 16 位有符号整数值 0 执行 Not 操作时很明显,该值将返回整数值 -1,换句话说,True = Not False.当对整数的各个位(例如 And、Or、Xor 和 Not)执行逻辑运算时,这种固有功能变得特别有用. [4]这种True的定义也与1970年代早期微软BASIC实现以来的BASIC一致,也与当时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天全站免登陆