BitConverter.ToInt32如何工作?

use*_*508 12 c# bit-manipulation

这是一种方法 -

using System;

class Program
{
    static void Main(string[] args)
    {
        //
        // Create an array of four bytes.
        // ... Then convert it into an integer and unsigned integer.
        //
        byte[] array = new byte[4];
        array[0] = 1; // Lowest
        array[1] = 64;
        array[2] = 0;
        array[3] = 0; // Sign bit
        //
        // Use BitConverter to convert the bytes to an int and a uint.
        // ... The int and uint can have different values if the sign bit differs.
        //
        int result1 = BitConverter.ToInt32(array, 0); // Start at first index
        uint result2 = BitConverter.ToUInt32(array, 0); // First index
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

16385 16385

我只是想知道这是怎么回事?

Jon*_*eet 14

文档BitConverter.ToInt32实际上有一些很好的例子.假设BitConverter.IsLittleEndian返回true,array[0]则是最低有效字节,正如您所示......虽然array[3]不仅仅是符号位,但它是包含符号位(作为位7)的最重要字节,但其余位用于大小.

所以在你的情况下,最低有效字节是1,下一个字节是64 - 所以结果是:

( 1 * (1 << 0) ) +    // Bottom 8 bits
(64 * (1 << 8) ) +    // Next 8 bits, i.e. multiply by 256
( 0 * (1 << 16)) +    // Next 8 bits, i.e. multiply by 65,536
( 0 * (1 << 24))      // Top 7 bits and sign bit, multiply by 16,777,216
Run Code Online (Sandbox Code Playgroud)

如果设置了符号位,则需要以不同的方式考虑这两种情况,但在这种情况下它很简单.

  • (试图抵制用`|`替换`+`的冲动; p) (3认同)

小智 4

它像以 256 为基数的数字一样进行转换。因此,在您的情况下:1+64*256 = 16385