Convert Boolean to Byte in VB.NET

Why does listing boolean on byte in .NET give the following result?

Snipp 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) 

Conclusion:

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

Why is True (usually called integer representation 1) converted to 255 when clicking on byte ?

+6
source share
4 answers

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

Conversion narrowing are conversions that cannot always be proven successful, conversions that are known to lose information, and conversions between type domains that are sufficiently different to merit narrowing of the 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 documents :

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

The byte is not signed, so you get instead of 255 instead of Two Compliment .

+11
source

The logical value True in .NET is saved as -1, and this, in turn, is 11111111 due to Two additions

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

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

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

+4
source

All historical versions of Basic that I saw that supported bitwise logical operators with integers used the value "all-bits-set", i.e. -1 as the value for true comparisons. Thus, if you want to have a value of 9 if a == b, or zero if not, you can use the expression 9 AND (a=b) . Although the ?: Operator present in C allows you to more clearly encode this behavior, using -1 for "truth" has more practical advantages than disadvantages in a language without a discrete Boolean type.

While vb.net is its own language, completely separate from vb6, there is a lot of code that has been ported from vb6 to vb.net, and can rely on the matching operators to give many bits when true.

+3
source

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

 Convert.ToByte(Boolean) 

Link to Convert.ToByte documentation (boolean) .

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

0
source

Source: https://habr.com/ru/post/908076/


All Articles