프로젝트

C#에서 union 사용하기(1)

BLDC 2017. 3. 1. 22:42

 

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

namespace unionTest
{
    class Program
    {
        [StructLayout(LayoutKind.Explicit)]
        struct INT_BYTE
        {
            [FieldOffset(0)]
            public int i;
            [FieldOffset(0)]
            public byte b0;
            [FieldOffset(1)]
            public byte b1;
            [FieldOffset(2)]
            public byte b2;
            [FieldOffset(3)]
            public byte b3;
        };
       
        static void Main(string[] args)
        {
            INT_BYTE x1 = new INT_BYTE();
            INT_BYTE x2 = new INT_BYTE();

 

            x1.i = 0x12345678;

 

            x2.b0 = x1.b0;
            x2.b1 = x1.b1;
            x2.b2 = x1.b2;
            x2.b3 = x1.b3;

 

            Console.WriteLine(" x2 = 0x{0:x} ", x2.i);
        }
    }
}