C# Convert an Ascii byte array to struct (i.e. with Marshal)

Viewed 28

i have a byte array that is sent through sockets. The byte array is a ascii string.

var bytes = Encoding.ASCII.GetBytes("00000250Q+0000SPS_22MFR   ");

How can i convert/marshal this byte array into a struct?

internal struct Header
{
    public ulong Size;
    public string Type;
    public ushort Sequence;
    public ushort ErrorCode;
    public string Sender;
    public string Receiver;
}

I already tried it with StructLayout and MarshalAs, but i get either an exception or a very different input/output.

[StructLayout(LayoutKind.Sequential, Size = 26, CharSet = CharSet.Ansi)]
internal struct SitTelegramHeader
{
    public ulong Size;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)] public string Type;
    public ushort Sequence;
    public ushort ErrorCode;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)] public string Sender;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)] public string Receiver;
}

enter image description here

Is there any way to do this with Marshal/BinaryFormatter/etc. or do i have to convert it by hand?

Thx for help.

0 Answers
Related