Beispiel #1
0
 /// <summary>
 /// 根据结构体成员标注的特性对结构体值的字节数组进行字节翻转
 /// </summary>
 private static byte[] RespectEndianness(byte[] bytes, Type type)
 {
     FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     foreach (FieldInfo field in fields)
     {
         if (field.IsDefined(typeof(EndianAttribute), false) && Marshal.SizeOf(field.FieldType) > 1)
         {
             EndianAttribute endianattr = (EndianAttribute)field.GetCustomAttributes(typeof(EndianAttribute), false)[0];
             if ((endianattr.Endian == Endianness.BigEndian && BitConverter.IsLittleEndian) || (endianattr.Endian == Endianness.LittleEndian && !BitConverter.IsLittleEndian))
             {
                 int mag = 1;
                 if (field.IsDefined(typeof(MarshalAsAttribute), false) && field.GetType().IsArray)
                 {
                     MarshalAsAttribute marshalattr = (MarshalAsAttribute)field.GetCustomAttributes(typeof(MarshalAsAttribute), false)[0];
                     mag = marshalattr.SizeConst > 1 ? marshalattr.SizeConst : 1;
                 }
                 for (int i = 0; i < mag; i++)
                 {
                     Array.Reverse(bytes, Marshal.OffsetOf(type, field.Name).ToInt32() + (i * Marshal.SizeOf(field.FieldType)), Marshal.SizeOf(field.FieldType));
                 }
             }
         }
     }
     return(bytes);
 }
Beispiel #2
0
 private static void RespectEndianness(Type type, byte[] data)
 {
     foreach (FieldInfo f in type.GetRuntimeFields())
     {
         if (f.IsDefined(typeof(EndianAttribute), false))
         {
             EndianAttribute att    = (EndianAttribute)f.GetCustomAttributes(typeof(EndianAttribute), false).GetEnumerator().Current;
             int             offset = Marshal.OffsetOf(type, f.Name).ToInt32();
             if ((att.Endianness == Endianness.BigEndian && BitConverter.IsLittleEndian) ||
                 (att.Endianness == Endianness.LittleEndian && !BitConverter.IsLittleEndian))
             {
                 Array.Reverse(data, offset, Marshal.SizeOf(f.FieldType));
             }
         }
     }
 }