안녕하세요,
오늘은 byte array to object / structure 형변환과 byte array to object / structure 형변환에 대해 포스팅 해보도록 하겠습니다.
형변환 소스코드
using System.Runtime.InteropServices;
public class Converter
{
/// <summary>
/// Convert object to byte array
/// </summary>
/// <param name="arr">Object to convert</param>
/// <returns>Converted byte array from the given object</returns>
public static byte[] ObjectToByte(object obj)
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
/// <summary>
/// Convert byte array to object
/// </summary>
/// <param name="arr">Byte array to convert</param>
/// <returns>Converted object from the given byte array</returns>
public static T ByteToObject<T>(byte[] arr) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
if (size > arr.Length)
{
throw new Exception();
}
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return obj;
}
}
Structure to UInt64의 경우 1) structure to byte array, 2) byte arry to UInt64의 작업을 통해 형 변환이 가능합니다. 이와 같이 위 메소드를 이용해 다양한 타입의 형 변환을 할 수 있습니다.
감사합니다.
'▶ 프로그래밍 [Programming] > ▷ C# 언어 [C# Language]' 카테고리의 다른 글
[C# 언어] bin string to int, int to bin string 변환 (0) | 2023.09.24 |
---|---|
[C# 언어] hex string to int, int to hex string 변환 (0) | 2023.09.23 |
댓글