반응형
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 메서드가 취해야 할 바이트의 위치를 직접 알려줘야 한다.
반응형
'C#' 카테고리의 다른 글
"WinForms 환경에서 Thread.Sleep vs 사용자 정의 Delay 함수: 차이점과 활용 방안" (0) | 2024.12.26 |
---|---|
"C# WinForms에서 멀티스레드로 안전하게 UI 컨트롤하기: InvokeRequired와 Invoke의 원리와 활용" (0) | 2024.12.18 |
C# partial 키워드 (1) | 2024.08.14 |
사용자 정의 타입 ArrayList.Sort (1) | 2024.08.01 |
프로퍼티 (1) | 2023.08.05 |
winform 시스템메뉴 MenuStrip 오른쪽버튼 (0) | 2023.07.22 |
as, is 연산자 (0) | 2023.07.16 |
숫자 구분자 사용 (2) | 2023.06.29 |