将整个byte []转换为uint

时间:2013-02-21 12:17:35

标签: c# .net

我的代码中有byte [] srno

byte[] srno = new byte[6];

srno[0] = 0xff;
srno[1] = 0x0f;
srno[2] = 0x24;
srno[3] = 0x12;
srno[4] = 0x16;
srno[5] = 0x0a;

现在我希望这个值在像

这样的uint中
uint a = 0xff0f2412160a;

如何转换?

3 个答案:

答案 0 :(得分:10)

正如@animaonline建议的那样,你应该使用BitConverter将字节数组转换为 uint 或* ulong。因此你有6个字节, uint 对你来说太小了。你应该转换为ulong *。但转换器需要8个字节,因此需要创建具有所需字节数的新数组:

byte[] value = new byte[8];
Array.Reverse(srno); // otherwise you will have a1612240fff result
Array.Copy(srno, value, 6);
ulong result = BitConverter.ToUInt64(value, 0);
Console.WriteLine("{0:x}", result); // ff0f2412160a

答案 1 :(得分:0)

在System命名空间中,您将找到BitConverter库类。您需要静态ToUInt64()函数,如下所示:

var a = BitConvert.ToUInt64(srno, 0);

您需要将数组的大小调整为[8]

MSDN

答案 2 :(得分:0)

每个人似乎都忽略了他预期输出的字节顺序编码。 BitConverter类使用固定编码(通常为Little-Endian,IIRC)。假设示例中的输出为Big-Endian。在一个完美的世界中,你只需要自己做数学,但使用Array.Reverse然后使用内置的BitConverter类更简单。

在我发布之前可能会有一堆答案,所以这里有一段非常快速的不安全代码:

public static unsafe ulong ToULong(byte[] values)
{
    byte* buffer = stackalloc byte[8];
    if (BitConverter.IsLittleEndian)
        Array.Reverse(values);
    System.Runtime.InteropServices.Marshal.Copy(values, 0, (IntPtr)buffer, values.Length);
    return *(ulong*)buffer;
}
相关问题