Giới thiệu
Phương thức BitConverter.ToSingle() trong C# chuyển đổi 4 byte từ một mảng byte (bắt đầu từ vị trí chỉ định) thành một số thực dấu chấm động đơn (float / Single).
Cú pháp
public static float ToSingle (byte[] value, int startIndex);
value: mảng byte nguồn.startIndex: chỉ số bắt đầu (0-based) trong mảng để đọc 4 byte.
Ví dụ 1: Mảng byte nhỏ
using System;
public class Demo {
public static void Main() {
byte[] arr = {0, 1, 2, 3, 5, 7, 10};
Console.WriteLine("Mảng Byte = " + BitConverter.ToString(arr));
for (int i = 0; i < arr.Length - 3; i += 4) {
float res = BitConverter.ToSingle(arr, i);
Console.WriteLine("\nGiá trị byte tại [" + i + "] = " + arr[i]);
Console.WriteLine("Kết quả float = " + res);
}
}
}
Đầu ra ví dụ 1
Mảng Byte = 00-01-02-03-05-07-0A Giá trị byte tại [0] = 0 Kết quả float = 3.820471E-37
Ví dụ 2: Mảng byte lớn hơn
using System;
public class Demo {
public static void Main() {
byte[] arr = {0, 10, 2, 5, 32, 45, 0, 0, 9, 20, 30, 50, 76, 88};
Console.WriteLine("Mảng Byte = " + BitConverter.ToString(arr));
for (int i = 0; i < arr.Length - 3; i += 4) {
float res = BitConverter.ToSingle(arr, i);
Console.WriteLine("\nGiá trị byte tại [" + i + "] = " + arr[i]);
Console.WriteLine("Kết quả float = " + res);
}
}
}
Đầu ra ví dụ 2
Mảng Byte = 00-0A-02-05-20-2D-00-00-09-14-1E-32-4C-58 Giá trị byte tại [0] = 0 Kết quả float = 6.114407E-36 Giá trị byte tại [4] = 32 Kết quả float = 1.61878E-41 Giá trị byte tại [8] = 9 Kết quả float = 9.201366E-09
Lưu ý quan trọng
- Endianness:
BitConverterphụ thuộc vào kiến trúc máy (little-endian trên x86/x64, big-endian trên một số kiến trúc khác). Kiểm traBitConverter.IsLittleEndian. - Cần đảm bảo
startIndex + 3 < value.Length,否则 némArgumentException. - Để chuyển đổi ngược (float → byte[]), dùng
BitConverter.GetBytes(floatValue). - Phương thức này thường dùng trong: network programming, file I/O binary, serialization, interop với C/C++.
Ví dụ thực tế: Round-trip
using System;
public class Demo {
public static void Main() {
float original = 3.14159f;
byte[] bytes = BitConverter.GetBytes(original);
Console.WriteLine("Bytes: " + BitConverter.ToString(bytes));
float restored = BitConverter.ToSingle(bytes, 0);
Console.WriteLine("Original: " + original);
Console.WriteLine("Restored: " + restored);
Console.WriteLine("Equal: " + (original == restored));
}
}
Đầu ra round-trip
Bytes: D0-0F-49-40 (little-endian) Original: 3.14159 Restored: 3.14159 Equal: True