/ Published in: C#
                    
                                        
See the URL for my question and answer on StackOverflow.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
public void Main()
{
0x80,
0x80,
0x80,
0x80,
0x80,0,
0x80,0,
0x80,0,0,0,
0x80,0,0,0,
0x80,0,0,0,0,0,0,0,
0x80,0,0,0,0,0,0,0,
// 0x3F,0x80,0,0,
// 0x3F,0xF0,0,0,0,0,0,0,
// 0x30,0,0,0,0,0,0,0,0,0,
0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0
};
0x80,
0x80,
0x80,
0x80,
0,0x80,
0,0x80,
0,0,0,0x80,
0,0,0,0x80,
0,0,0,0,0,0,0,0x80,
0,0,0,0,0,0,0,0x80,
// 0,0,0x80,0x3F,
// 0,0,0,0,0,0,0xF0,0x3F,
// 0x30,0,0,0,0,0,0,0,0,0,
0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0
};
Foo fooLe = ByteArrayToStructure<Foo>(leBytes).Dump("LE");
Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes,
"bbbbsSiIlL"
// + "fd"
+"9bb").Dump("BE");
// Assert.AreEqual(fooLe, fooBe);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Foo {
public byte b1;
public byte b2;
public byte b3;
public byte b4;
public short s;
public ushort S;
public int i;
public uint I;
public long l;
public ulong L;
// public float f;
// public double d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string MyString;
}
T ByteArrayToStructure<T>(byte[] bytes) where T: struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
handle.Free();
return stuff;
}
T ByteArrayToStructureBigEndian<T>(byte[] bytes, string description) where T: struct
{
byte[] buffer = bytes;
IList unpacked = DataConverter.Unpack("^"+description, buffer, 0).Dump("unpacked");
buffer = DataConverter.PackEnumerable("!"+description, unpacked).Dump("packed");
return ByteArrayToStructure<T>(buffer);
}
Comments
 Subscribe to comments
                    Subscribe to comments
                
                