BitConverter Class-主要用于Byte类型转换

C# 中的 BitConverter 类提供了一系列静态方法,用于将基本数据类型转换为字节数组和从字节数组转换回基本类型。这个例子展示了如何使用这些方法,包括 Double、Single、Long、Int、Short、Char 和 Boolean 的转换。需要注意的是,字节顺序(小端或大端)取决于计算机体系结构,可能导致在不同系统间传输数据时出现问题。在处理字节数据时,确保正确处理字节序以避免数据错误。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

定义

命名空间:

系统

集会:

系统运行时文件

将基本数据类型转换为字节数组,将字节数组转换为基本数据类型。

C#复制
public static class BitConverter

遗产

位转换器

例子

下面的代码示例说明了几个BitConverter类方法的使用。

// Example of BitConverter class methods.
using System;

class BitConverterDemo
{
    public static void Main( )
    {
        const string formatter = "{0,25}{1,30}";

        double  aDoubl  = 0.1111111111111111111;
        float   aSingl  = 0.1111111111111111111F;
        long    aLong   = 1111111111111111111;
        int     anInt   = 1111111111;
        short   aShort  = 11111;
        char    aChar   = '*';
        bool    aBool   = true;

        Console.WriteLine(
            "This example of methods of the BitConverter class" +
            "\ngenerates the following output.\n" );
        Console.WriteLine( formatter, "argument", "byte array" );
        Console.WriteLine( formatter, "--------", "----------" );

        // Convert values to Byte arrays and display them.
        Console.WriteLine( formatter, aDoubl,
            BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) );
        Console.WriteLine( formatter, aSingl,
            BitConverter.ToString( BitConverter.GetBytes( aSingl ) ) );
        Console.WriteLine( formatter, aLong,
            BitConverter.ToString( BitConverter.GetBytes( aLong ) ) );
        Console.WriteLine( formatter, anInt,
            BitConverter.ToString( BitConverter.GetBytes( anInt ) ) );
        Console.WriteLine( formatter, aShort,
            BitConverter.ToString( BitConverter.GetBytes( aShort ) ) );
        Console.WriteLine( formatter, aChar,
            BitConverter.ToString( BitConverter.GetBytes( aChar ) ) );
        Console.WriteLine( formatter, aBool,
            BitConverter.ToString( BitConverter.GetBytes( aBool ) ) );
    }
}

/*
This example of methods of the BitConverter class
generates the following output.

                 argument                    byte array
                 --------                    ----------
        0.111111111111111       1C-C7-71-1C-C7-71-BC-3F
                0.1111111                   39-8E-E3-3D
      1111111111111111111       C7-71-C4-2B-AB-75-6B-0F
               1111111111                   C7-35-3A-42
                    11111                         67-2B
                        *                         2A-00
                     True                            01
*/

评论

BitConverter类有助于其基本形式操作的值类型,作为一系列的字节。一个字节被定义为一个 8 位无符号整数。所述BitConverter类包括静态方法给每个基本数据类型的转换,并从一个字节数组,如下面的表所示。

如果您使用BitConverter方法来往返数据,请确保GetBytes重载和ToType方法指定相同的类型。如以下示例所示,通过调用ToUInt32方法还原表示有符号整数的数组可能会产生与原始值不同的值。有关更多信息,请参阅使用有符号非十进制值和按位值

C#复制
跑步
using System;

public class Example
{
   public static void Main()
   {
      int value = -16;
      Byte[] bytes = BitConverter.GetBytes(value);

      // Convert bytes back to int.
      int intValue = BitConverter.ToInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}",
                        value, intValue,
                        value.Equals(intValue) ? "Round-trips" : "Does not round-trip");
      // Convert bytes to UInt32.
      uint uintValue = BitConverter.ToUInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}", value, uintValue,
                        value.Equals(uintValue) ? "Round-trips" : "Does not round-trip");
   }
}
// The example displays the following output:
//       -16 = -16: Round-trips
//       -16 = 4294967280: Does not round-trip

GetBytes方法重载返回的数组中的字节顺序(以及DoubleToInt64Bits方法返回的整数中的位顺序和ToString(Byte[])方法返回的十六进制字符串的顺序)取决于计算机体系结构是小端或大端。同样,由ToIntegerValue方法和ToChar方法返回的数组中的字节顺序取决于计算机体系结构是小端还是大端。架构的字节序由IsLittleEndian属性指示,它返回true小端系统和false在大端系统上。在小端系统上,低位字节在高位字节之前。在大端系统上,高位字节在低位字节之前。下表说明了将整数 1,234,567,890 (0x499602D2) 传递给GetBytes(Int32)方法所产生的字节数组的差异。字节按从索引 0 处的字节到索引 3 处的字节的顺序列出。

表 2
Little-endianD2-02-96-49
Big-endian49-96-02-D2

由于某些方法的返回值取决于系统架构,因此在超出机器边界传输字节数据时要小心:

  • 如果所有发送和接收数据的系统都保证具有相同的字节序,则不会对数据执行任何操作。

  • 如果发送和接收数据的系统可以有不同的字节序,请始终按特定顺序传输数据。这意味着数组中的字节顺序可能必须在发送之前或接收之后颠倒。一个常见的约定是以网络字节顺序(大端顺序)传输数据。以下示例提供了一种以网络字节顺序发送整数值的实现。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          int value = 12345678;
          byte[] bytes = BitConverter.GetBytes(value);
          Console.WriteLine(BitConverter.ToString(bytes));
    
          if (BitConverter.IsLittleEndian)
             Array.Reverse(bytes);
    
          Console.WriteLine(BitConverter.ToString(bytes));
          // Call method to send byte stream across machine boundaries.
    
          // Receive byte stream from beyond machine boundaries.
          Console.WriteLine(BitConverter.ToString(bytes));
          if (BitConverter.IsLittleEndian)
             Array.Reverse(bytes);
    
          Console.WriteLine(BitConverter.ToString(bytes));
          int result = BitConverter.ToInt32(bytes, 0);
          Console.WriteLine("Original value: {0}", value);
          Console.WriteLine("Returned value: {0}", result);
       }
    }
    // The example displays the following output on a little-endian system:
    //       4E-61-BC-00
    //       00-BC-61-4E
    //       00-BC-61-4E
    //       4E-61-BC-00
    //       Original value: 12345678
    //       Returned value: 12345678
    
  • 如果系统有符号整数的发送和接收的数据可以具有不同的字节序和将被发送的数据包括,调用IPAddress.HostToNetworkOrder方法来将数据转换为网络字节顺序和IPAddress.NetworkToHostOrder方法将其转换为通过将所需的次序接受者。

字段

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值