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

Phương thức BitConverter.ToInt64() trong C#

Phương thức BitConverter.ToInt64(byte[] value, int startIndex) chuyển đổi 8 byte bắt đầu từ vị trí startIndex trong mảng byte thành một số nguyên 64-bit có dấu (long).

Cú pháp

public static long ToInt64(byte[] value, int startIndex);

Ví dụ 1: Chuyển đổi mảng byte đơn giản

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = { 0, 10, 15, 20, 26, 30, 34, 42, 50 };
        Console.WriteLine("Mảng byte = {0}", BitConverter.ToString(arr));

        for (int i = 0; i < arr.Length - 7; i += 8)
        {
            long res = BitConverter.ToInt64(arr, i);
            Console.WriteLine("\nGiá trị byte tại [{0}] = {1}", i, arr[i]);
            Console.WriteLine("Kết quả ToInt64 = {0}", res);
        }
    }
}

Kết quả

Mảng byte = 00-0A-0F-14-1A-1E-22-2A-32
Giá trị byte tại [0] = 0
Kết quả ToInt64 = 3036022196155648512

Ví dụ 2: Mảng byte nhiều giá trị 0

using System;

public class Demo
{
    public static void Main()
    {
        byte[] arr = {0, 0, 0, 10, 20, 0, 0, 25, 30, 0, 0, 0, 35, 45, 55, 65, 75};
        Console.WriteLine("Mảng byte = {0}", BitConverter.ToString(arr));

        for (int i = 0; i < arr.Length - 7; i += 8)
        {
            long res = BitConverter.ToInt64(arr, i);
            Console.WriteLine("\nGiá trị byte tại [{0}] = {1}", i, arr[i]);
            Console.WriteLine("Kết quả ToInt64 = {0}", res);
        }
    }
}

Kết quả

Mảng byte = 00-00-00-0A-14-00-00-19-1E-00-00-00-23-2D-37-41-4B
Giá trị byte tại [0] = 0
Kết quả ToInt64 = 1801439937015316480
Giá trị byte tại [8] = 30
Kết quả ToInt64 = 4699274364531507230

Lưu ý: Thứ tự byte (endianness) phụ thuộc vào kiến trúc máy. Kết quả có thể khác nhau giữa little-endian và big-endian.