create a union of int and four bytes in csharp

You can create a union of an int and four bytes in C# using the unsafe keyword and a fixed block to pin the memory. Here's an example:

main.cs
using System;

unsafe struct IntAndFourBytesUnion {
    public int IntValue;
    public fixed byte Bytes[4];
}

class Program {
    static void Main(string[] args) {
        IntAndFourBytesUnion union = new IntAndFourBytesUnion();
        union.IntValue = 0x11223344;

        Console.WriteLine(BitConverter.ToString(union.Bytes)); // Output: 44-33-22-11
    }
}
363 chars
16 lines

In this example, we define a struct called IntAndFourBytesUnion with two members: an int called IntValue and a fixed array of four bytes called Bytes. We then create an instance of this struct, set the IntValue to 0x11223344, and print out the bytes using BitConverter.ToString(). The output shows that the bytes have been reversed, which is due to endianness issues.

gistlibby LogSnag