布尔转换为字节VB.NET布尔、转换为、字节、NET

2023-09-03 16:27:10 作者:半醉半醒半浮生

为什么在.NET中铸造了布尔字节给出以下输出?

Why does casting a boolean to a byte in .NET give the following output?

code的这段:

Dim x As Boolean = 1
Dim y As Byte = x    'Implicit conversion here from Boolean to Byte

System.Diagnostics.Debug.Print( _
    "x = " & x.ToString _
    & " y = " & y.ToString _
    & " (bool)(1) = " & CType(1, Boolean).ToString _
    & " (byte)((bool)1) = " & CType((CType(1, Boolean)), Byte).ToString)

输出:

X =真   Y = 255   (布尔)(1)=真   (字节)((布尔)1)= 255

x = True y = 255 (bool)(1) = True (byte)((bool)1) = 255

为什么(这通常被称为重1 presentation整数)转换为255,当铸造到字节

Why does True (which commonly is referred to as an integer representation of 1) convert to 255 when casted to a byte?

推荐答案

在VB.NET编译器将它作为一个收缩转换。从10.0 VB.NET规格:

The VB.NET compiler handles it as a narrowing conversion. From the 10.0 VB.NET Spec:

缩小转换是不能被证明总是成功的转换,已知有可能丢失信息的转换和跨类型的不同,以至值得缩小符号域转换。下面的转换属于收缩转换:

Narrowing conversions are conversions that cannot be proved to always succeed, conversions that are known to possibly lose information, and conversions across domains of types sufficiently different to merit narrowing notation. The following conversions are classified as narrowing conversions:   从布尔值,字节,为SByte,USHORT,短,UInteger,整型,ULONG,龙,小数,单,或双。   

从的文档:

在Visual Basic中转换成数字数据类型值布尔值,0变成假,所有其他值成真。在Visual Basic中的布尔值转换为数字类型,假变为0,真正变为-1。

VB6.0如何转换C VB.Net如何转换C

When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True. When Visual Basic converts Boolean values to numeric types, False becomes 0 and True becomes -1.

字节的未签名,让你从二进制补得到255个吧。

Byte's aren't signed, so you get 255 instead from Two's Compliment.