布尔转换为字节VB.NET [英] Converting Boolean to Byte in VB.NET

查看:470
本文介绍了布尔转换为字节VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在.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。

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.

这篇关于布尔转换为字节VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆