Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
afuzzyllama Avatar asked Feb 09 '12 19:02

afuzzyllama


1 Answers

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.

like image 104
vcsjones Avatar answered Sep 28 '22 02:09

vcsjones