프로젝트

c#에서 union 사용하기(3)

BLDC 2017. 3. 2. 22:40

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace unionTest
{
    class Program
    {
        [StructLayout(LayoutKind.Explicit)]
        public unsafe struct INT_BYTE
        {
            [FieldOffset(0)]
            public int i;
            [FieldOffset(0)]
            public fixed byte b[4];
        };
        public INT_BYTE x1 = new INT_BYTE();

        static void Main(string[] args)
        {
            Program pg = new Program();

            byte[] x2 = new byte[4];

            x2[0] = 0x44;
            x2[1] = 0x33;
            x2[2] = 0x22;
            x2[3] = 0x11;

            unsafe
            {
                fixed (INT_BYTE* p = &pg.x1)
                {
                    for (int k = 0; k < 4; k++)
                    {
                        p->b[k] = x2[k];
                    }
                }
            }
            Console.WriteLine(" x1.i = 0x{0:x} ", pg.x1.i);
        }
    }
}