gpt4 book ai didi

c# - BitConverter.ToInt32 是如何工作的?

转载 作者:可可西里 更新时间:2023-11-01 08:20:06 27 4
gpt4 key购买 nike

这是一个方法-

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();
}
}

输出

1638516385

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

最佳答案

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

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

关于c# - BitConverter.ToInt32 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com