gpt4 book ai didi

C#、BitConverter.ToUInt32、不正确的值

转载 作者:行者123 更新时间:2023-11-30 14:57:23 25 4
gpt4 key购买 nike

我尝试将 IP 地址转换为长值:

byte[] Ip = new byte[4] { 192, 168, 1, 0 };

UInt32 Ret1 = (((UInt32)Ip[0]) << 24) |
(((UInt32)Ip[1]) << 16) |
(((UInt32)Ip[2]) << 8) |
(((UInt32)Ip[3]));

UInt32 Ret2 = BitConverter.ToUInt32(Ip, 0);

Ret1 返回 3232235776(正确值)

Ret2 返回 108736 (?)

为什么会有这种差异?

最佳答案

确实,字节顺序是您的问题。虽然不难解决,但有时在基于 Intel 的系统上会很烦人,因为它们处于 Little EndianNetwork OrderBig Endian .简而言之,您的字节顺序相反。

这里有一些您可以用来解决这个问题(甚至在各种平台上)的便捷方法:

static uint MakeIPAddressInt32(byte[] array)
{
// Make a defensive copy.
var ipBytes = new byte[array.Length];
array.CopyTo(ipBytes, 0);

// Reverse if we are on a little endian architecture.
if(BitConverter.IsLittleEndian)
Array.Reverse(ipBytes);

// Convert these bytes to an unsigned 32-bit integer (IPv4 address).
return BitConverter.ToUInt32(ipBytes, 0);
}

关于C#、BitConverter.ToUInt32、不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892093/

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