C#从byte []转换为struct.字节顺序错误 [英] C# Converting from byte[] to struct. The byte order is wrong

查看:107
本文介绍了C#从byte []转换为struct.字节顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现基于UDP的协议时,我试图使用一种结构来解析套接字数据. 我进行了搜索,可以使用这两个函数在byte []和struct之间进行转换:

I was trying to use a struct to parse socket data when implement a UDP based protocol. And I searched and I can use these 2 functions to convert between byte[] and struct:

 byte[] StructToBytes(object structObj)
    {
        int size = Marshal.SizeOf(structObj);
        IntPtr buffer = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.StructureToPtr(structObj, buffer, false);
            byte[] bytes = new byte[size];
            Marshal.Copy(buffer, bytes, 0, size);
            return bytes;
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }

    }

    static object BytesToStruct(byte[] bytes, Type strcutType, int offset = 0)
    {
        int size = Marshal.SizeOf(strcutType);
        IntPtr buffer = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.Copy(bytes, offset, buffer, size);
            return Marshal.PtrToStructure(buffer, strcutType);
        }
        finally
        {
            Marshal.FreeHGlobal(buffer);
        }
    }

然后我遇到了这个问题:

Then I had this problem:

//I defined a simple struct with an ushort member
    [StructLayout(LayoutKind.Sequential, Pack = 2)]
    struct S
    {
        public ushort a;
    }

    //Then I define a byte[]
    byte[] bArr;
    bArr[0] = 0;
    bArr[1] = 1;

    //Convert to struct
    S s = (S)BytesToStruct(bArr, typeof(S));
    //Then s.a = 0x0100 not 0x0001

与byte []的结构相同. ushort的2个字节被颠倒了. 我该如何解决这个问题?

And struct to byte[] is just the same. The 2 bytes of ushort are reversed. How do I solve this problem?

推荐答案

如今,大多数处理器都使用Little-Endian字节排序(最低有效字节排在第一位).网络字节顺序是传统的Big-Endian,因此通常需要镜像字节顺序.您可以使用System.BitConverter.IsLittleEndian

Most processors these days use Little-Endian byte ordering (Least significant byte comes first). Network byte ordering is traditional Big-Endian, so you usually need to mirror the byte order. You can check the endianness of the system with System.BitConverter.IsLittleEndian

提到的ntohs()Frank的.Net等价物(奇怪地)位于System.Net.IPAddress.NetworkToHostOrder()

The .Net equivalent of ntohs() Frank mentioned is located (oddly) at System.Net.IPAddress.NetworkToHostOrder()

您还可以编写自己的机制,以使用移位和逻辑或直接按正确的顺序读取字节.

You could also write your own mechanism to read the bytes in the correct order directly, using bit shifting and logical OR.

这篇关于C#从byte []转换为struct.字节顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆