Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5930743
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T14:35:45+00:00 2026-05-22T14:35:45+00:00

There is an insightful question about reading a C/C++ data structure in C# from

  • 0

There is an insightful question about reading a C/C++ data structure in C# from a byte array, but I cannot get the code to work for my collection of big-endian (network byte order) bytes. (EDIT: Note that my real struct has more than just one field.) Is there a way to marshal the bytes into a big-endian version of the structure and then pull out the values in the endianness of the framework (that of the host, which is usually little-endian)?

(Note, reversing the array of bytes will not work – each value’s bytes must be reversed, which does not give you the same collection as reversing all of the bytes.)

This should summarize what I’m looking for (LE=LittleEndian, BE=BigEndian):

void Main()
{
    var leBytes = new byte[] {1, 0, 2, 0};
    var beBytes = new byte[] {0, 1, 0, 2};
    Foo fooLe = ByteArrayToStructure<Foo>(leBytes);
    Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes);
    Assert.AreEqual(fooLe, fooBe);
}

[StructLayout(LayoutKind.Explicit, Size=4)]
public struct Foo  {
    [FieldOffset(0)] 
    public ushort firstUshort;
    [FieldOffset(2)] 
    public ushort secondUshort;
}

T ByteArrayToStructure<T>(byte[] bytes) where T: struct 
{
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));
    handle.Free();
    return stuff;
}

T ByteArrayToStructureBigEndian<T>(byte[] bytes) where T: struct 
{
    ???
}

Other helpful links:

Byte of a struct and onto endian concerns

A little more on bytes and endianness (byte order)

Read binary files more efficiently using C#

Unsafe and reading from files

Mono’s contribution to the issue

Mastering C# structs

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T14:35:45+00:00Added an answer on May 22, 2026 at 2:35 pm

    As alluded to in my comment on @weismat’s answer, there is an easy way to achieve big-endian structuring. It involves a double-reversal: the original bytes are reversed entirely, then the struct itself is the reversal of the original (big-endian) data format.

    The fooLe and fooBe in Main will have the same values for all fields. (Normally, the little-endian struct and bytes wouldn’t be present, of course, but this clearly shows the relationship between the byte orders.)

    NOTE: See updated code including how to get bytes back out of the struct.

    public void Main()
    {
        var beBytes = new byte[] {
            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, // float of 1 (see http://en.wikipedia.org/wiki/Endianness#Floating-point_and_endianness)
            0x3F,0xF0,0,0,0,0,0,0, // double of 1
            0,0,0,0x67,0x6E,0x69,0x74,0x73,0x65,0x54 // Testing\0\0\0
        };
        var leBytes = new byte[] {
            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, // float of 1
            0,0,0,0,0,0,0xF0,0x3F, // double of 1
            0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0 // Testing\0\0\0
        };
        Foo fooLe = ByteArrayToStructure<Foo>(leBytes).Dump("LE");
        FooReversed fooBe = ByteArrayToStructure<FooReversed>(beBytes.Reverse().ToArray()).Dump("BE");  
    }
    
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Foo  {
        public byte b1;
        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;
    }
    
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct FooReversed  {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
        public string MyString;
        public double d;
        public float f;
        public ulong L;
        public long l;
        public uint I;
        public int i;
        public ushort S;
        public short s;
        public byte b1;
    }
    
    T ByteArrayToStructure<T>(byte[] bytes) where T: struct 
    {
        GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
        T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));
        handle.Free();
        return stuff;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There's a lot of reading on self referencing problems, but I can't seem to
There is about 2000 lines of this, so manually would probably take more work
There is a lot of information about composition vs inheritance online, but I haven't
There are a few ways to get class-like behavior in javascript, the most common
There are numerous libraries providing Linq capabilities to C# code interacting with a MySql
As far as I can see, a pointer to structure can be used. But
I've written a log parser, with some generous and insightful help from the SO
I work for a boutique specialized in finance. We thought about designing a language
There is something I miss with the notion of Synchronizing code in Android. Scenario
This question is more or less the same as Restrict Certain Java Code in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.