C# 中的 BitConverter 类

csharpserver side programmingprogramming更新于 2025/9/13 21:10:00

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

以下是方法 −

方法说明
DoubleToInt64Bits(Double)将指定的双精度浮点数转换为 64 位有符号整数。
GetBytes(Boolean)以字节数组形式返回指定的布尔值。
GetBytes(Char)返回指定的 Unicode字符值作为字节数组返回。
GetBytes(Double)以字节数组的形式返回指定的双精度浮点值。
GetBytes(Int16)以字节数组的形式返回指定的 16 位有符号整数值。
GetBytes(Int32)以字节数组的形式返回指定的 32 位有符号整数值。
Int64BitsToDouble(Int64)将指定的 64 位有符号整数重新解释为双精度浮点数。
ToBoolean(Byte[], Int32)返回从字节数组中指定位置的字节。
ToChar(Byte[], Int32)返回由字节数组中指定位置的两个字节转换而来的 Unicode 字符。
ToString(Byte[])将指定字节数组的每个元素的数值转换为其等效的十六进制字符串表示形式。
ToString(Byte[], Int32)将指定字节子数组的每个元素的数值转换为其等效的十六进制字符串表示形式。
ToString(Byte[], Int32, Int32)将指定字节子数组的每个元素的数值转换为其等效的十六进制字符串表示形式。
ToString(Byte[], Int32, Int32)将指定字节子数组的每个元素的数值转换为其等效的十六进制字符串表示。
ToUInt16(Byte[], Int32)返回从字节数组中指定位置的两个字节转换而来的 16 位无符号整数。

让我们看一些例子 −

C# 中的 BitConverter.ToBoolean() 方法返回从字节数组中指定位置的字节转换而来的布尔值。

语法

以下是语法 −

public static bool ToBoolean (byte[] arr, int startIndex);

上面,arr 是一个字节数组,而 startIndex 是值中字节的索引。

示例

现在让我们看一个实现 BitConverter.ToBoolean() 方法 − 的示例

using System;
public class Demo {
   public static void Main(){
      byte[] arr = { 50, 100 };
      Console.WriteLine("数组值...");
      for (int i = 0; i < arr.Length; i++) {
           Console.WriteLine("{0} ", arr[i]);
      }
      Console.WriteLine("
转换后的值...");       for (int index = 0; index < arr.Length; index++) {           bool res = BitConverter.ToBoolean(arr, index);          Console.WriteLine(""+res);       }    } }

输出

将产生以下输出 −

数组值...
50
100
转换后的值...
True
True

C# 中的 BitConverter.DoubleToInt64Bits() 方法用于将指定的双精度浮点数转换为 64 位有符号整数。

语法

以下是语法 −

public static long DoubleToInt64Bits (double val);

上面,val 是要转换的数字。

示例

现在让我们看一个实现 BitConverter.DoubleToInt64Bits() 方法的示例 −

using System;
public class Demo {
   public static void Main(){
      double d = 5.646587687;
      Console.Write("Value = "+d);
      long res = BitConverter.DoubleToInt64Bits(d);
      Console.Write("
64-bit signed integer = "+res);    } }

输出

这将产生以下输出 −

Value = 5.646587687 
64-bit signed integer = 4618043510978159912

相关文章