简体   繁体   中英

Converting Boolean to Byte in VB.NET

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

Code Snippit:

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)

Output:

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

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

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:

  • From Boolean to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

From the docs :

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.

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

A boolean value of True in .NET is stored as -1, which in turn is 11111111 due to Two's Complement

So Dim x As Boolean = 1 converts 1 to Boolean True

and Dim y As Byte = x converts True to 11111111, which equals 255

(If instead you wrote Dim z As Integer = x , z would = -1)

All historical versions of Basic I've seen which have supported bitwise Boolean operators with integers have used "all-bits-set", ie -1, as the value for true comparisons. Thus, if one wanted to have a value that was 9 if a==b, or zero if not, one could use the expression 9 AND (a=b) . While the ?: operator present in C allows such behavior to be coded more clearly, the use of -1 for "true" has more practical advantages than disadvantages in a language without a discrete Boolean type.

While vb.net is its own language, quite separate from vb6, there is a lot of code which has been ported from vb6 to vb.net, and may rely upon the fact that comparison operators yield all-bits-set when true.

If you want to convert true to 1 and false to 0 , use:

Convert.ToByte(Boolean) 

Link to documentation Convert.ToByte(boolean) .

Otherwise yo get the real value -1 , 0xFF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM