Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp BitConverter trong C#

Giới thiệu

Lớp BitConverter trong namespace System cung cấp các phương thức tĩnh để chuyển đổi giữa các kiểu dữ liệu cơ bản (base types) và mảng byte (byte[]). Điều này rất hữu ích khi làm việc với I/O nhị phân, mạng, serialization, hoặc tương tác với code không quản lý (unmanaged).

Các phương thức chính

Phương thức Mô tả
GetBytes(bool) Chuyển Boolean thành mảng byte (1 byte).
GetBytes(char) Chuyển Unicode char thành mảng byte (2 byte).
GetBytes(short) / GetBytes(int) / GetBytes(long) Chuyển số nguyên có dấu thành mảng byte (2/4/8 byte).
GetBytes(ushort) / GetBytes(uint) / GetBytes(ulong) Chuyển số nguyên không dấu thành mảng byte.
GetBytes(float) / GetBytes(double) Chuyển số thực thành mảng byte (4/8 byte).
ToBoolean(byte[], int) Chuyển 1 byte tại vị trí chỉ định thành Boolean.
ToChar(byte[], int) Chuyển 2 byte tại vị trí chỉ định thành char.
ToInt16/ToInt32/ToInt64(byte[], int) Chuyển byte thành số nguyên có dấu.
ToUInt16/ToUInt32/ToUInt64(byte[], int) Chuyển byte thành số nguyên không dấu.
ToSingle/ToDouble(byte[], int) Chuyển byte thành số thực.
ToString(byte[]) / ToString(byte[], int) / ToString(byte[], int, int) Chuyển mảng byte thành chuỗi hex (ví dụ: "0A-1F-3C").
DoubleToInt64Bits(double) Lấy biểu diễn bit 64-bit của double (IEEE 754).
Int64BitsToDouble(long) Chuyển bit 64-bit thành double.

Ví dụ 1: BitConverter.ToBoolean()

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 50, 100 };
        Console.WriteLine("Giá trị mảng byte...");
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine("{0}", arr[i]);
        }

        Console.WriteLine("\nChuyển đổi sang Boolean...");
        for (int index = 0; index < arr.Length; index++)
        {
            bool res = BitConverter.ToBoolean(arr, index);
            Console.WriteLine(res);
        }
    }
}

Kết quả

Giá trị mảng byte...
50
100
Chuyển đổi sang Boolean...
True
True

Giải thích: Bất kỳ byte nào khác 0 đều chuyển thành true, chỉ byte 0 mới thành false.

Ví dụ 2: BitConverter.DoubleToInt64Bits()

using System;

public class Demo
{
    public static void Main()
    {
        double d = 5.646587687;
        Console.Write("Giá trị = " + d);
        long res = BitConverter.DoubleToInt64Bits(d);
        Console.Write("\nSố nguyên 64-bit có dấu = " + res);
    }
}

Kết quả

Giá trị = 5.646587687
Số nguyên 64-bit có dấu = 4618043510978159912

Ví dụ 3: Chuyển đổi số nguyên và float

using System;

public class Demo
{
    public static void Main()
    {
        int value = 123456;
        byte[] bytes = BitConverter.GetBytes(value);
        Console.WriteLine("Int {0} -> Byte array: {1}", value, BitConverter.ToString(bytes));

        float f = 3.14159f;
        bytes = BitConverter.GetBytes(f);
        Console.WriteLine("Float {0} -> Byte array: {1}", f, BitConverter.ToString(bytes));

        // Chuyển ngược
        int back = BitConverter.ToInt32(bytes, 0);
        Console.WriteLine("Byte array -> Int: " + back);
    }
}

Lưu ý quan trọng

  • Endianness: Kết quả phụ thuộc vào kiến trúc CPU (Little-endian trên x86/x64, Big-endian trên một số ARM). Dùng BitConverter.IsLittleEndian để kiểm tra.
  • Để code portable, cân nhắc dùng BinaryPrimitives (.NET Core 2.1+) hoặc tự xử lý endianness.
  • ToString(byte[]) định dạng hex với dấu gạch nối (-), rất tiện cho debug/log.
  • Chuyển đổi struct phức tạp: dùng MemoryMarshal hoặc BinaryReader/BinaryWriter.