본문 바로가기
C#

System.IO.MemoryStream

by 공부봇 2024. 8. 1.
반응형

System.IO.MemoryStream

 

MemoryStream 타입은 이름 그대로 메모리에 바이트 데이터를 순서대로 읽고 쓰는 작업을 수행하는 클래스다.

이를 이용하면 데이터를 메모리에 직렬화/역직렬화하는것이 가능하다.

 

            // short와 int 데이터를 순서대로 memorystream에 직렬화. 
            byte[] shortBytes = BitConverter.GetBytes((short)32000);
            byte[] intBytes   = BitConverter.GetBytes(1652300);

            MemoryStream ms = new MemoryStream();
            ms.Write(shortBytes, 0, shortBytes.Length);
            ms.Write(intBytes,   0, intBytes.Length);

            ms.Position = 0;
            
            // Memorystream으로부터 short 데이터를 역직렬화.
            byte[] outBytes = new byte[2];
            ms.Read(outBytes, 0, 2);
            short shortResult = BitConverter.ToInt16(outBytes, 0);
            Console.WriteLine(shortResult);

            outBytes = new byte[4];
            ms.Read(outBytes, 0, 4);
            int intResult = BitConverter.ToInt32(outBytes, 0);
            Console.WriteLine(intResult);

 

MemoryStream이 내부적으로 유지하고 있는 바이트 배열을 얻기 위해 ToArray 메서드를 호출할 수 있다. 

            byte[] buf = ms.ToArray();

            // 바이트 배열로부터 short 데이터를 역직렬화
            short shortResult = BitConverter.ToInt16(buf, 0);
            Console.WriteLine(shortResult);

            int intResult = BitConverter.ToInt32(buf, 2);
            Console.WriteLine(intResult);

byte 배열에는 Position의 기능이 없으므로 ToInt32 메서드가 취해야 할 바이트의 위치를 직접 알려줘야 한다. 

 

 

반응형