C#中遇到问题时,转换的byte []到结构体。字节顺序是错误的 [英] C# Encounter a problem when convert byte[] to struct. The byte order is wrong

查看:575
本文介绍了C#中遇到问题时,转换的byte []到结构体。字节顺序是错误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用结构时,实现一个基于UDP协议来解析套接字的数据。
和我搜索,我可以利用这两个功能的byte []和结构之间的转换:

I was trying to using 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 []仅仅是相同。的2字节USHORT的反转。
我该如何解决这个问题?

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

推荐答案

这些天使用little-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

在.NET相当于ntohs和的()弗兰克提到位于(奇怪)在 System.Net.IPAddress.NetworkToHostOrder()

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

您也可以写你的自己的机制来读取直接按正确的顺序字节,使用位移位和逻辑OR。

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

这篇关于C#中遇到问题时,转换的byte []到结构体。字节顺序是错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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