代码之家  ›  专栏  ›  技术社区  ›  Paul Farry

字节=8位,但为什么位转换器不这么认为

  •  2
  • Paul Farry  · 技术社区  · 16 年前

    提供以下信息

    Public Enum Request As Byte
        None = 0
        Identity = 1
        License = 2
    End Enum
    
    Protected mType As Communication.Request
    
    mType = Communication.Request.Identity
    
    Debug.Print (BitConverter.GetBytes(mType).Length.tostring)
    
    2
    

    为什么bitconverter报告mType的长度是2。我本以为将字节传递到bitconverter.GetBytes只会返回字节。

    我的意思是这没什么大不了的,因为它只是通过TCP套接字发送一个非常小的数据块,但我只是好奇为什么它认为它是2字节。

    1 回复  |  直到 16 年前
        1
  •  6
  •   Femaref    16 年前

    因为BitConverter.GetBytes(Byte b)没有重载(请参阅 msdn ),则使用最近的可用隐式重载,在本例中,它返回一个字节[2]。

    使用简单代码:

            byte b = 1;
            BitConverter.GetBytes(b);
    

    通过编译并使用ildasm,我们可以看到int16(简称)的方法被称为:

    .method public hidebysig instance void  bytetest() cil managed
    {
      // Code size       11 (0xb)
      .maxstack  1
      .locals init ([0] uint8 b)
      IL_0000:  nop
      IL_0001:  ldc.i4.1
      IL_0002:  stloc.0
      IL_0003:  ldloc.0
      IL_0004:  call       uint8[] [mscorlib]System.BitConverter::GetBytes(int16)
      IL_0009:  pop
      IL_000a:  ret
    } // end of method Test::bytetest