언어/C#

[C#] 바이트 배열을 int로, int를 바이트 배열로

돌멩이수프 2022. 6. 4. 23:00
728x90
using System;
using System.Threading;

namespace Study
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = { 0, 0, 0, 25 };
            if (BitConverter.IsLittleEndian) // 오른쪽 끝에 중요한 게 있다
                Array.Reverse(bytes); // 배열을 반대로 정렬 (중요한 걸 왼쪽 끝으로 이동)
            int i = BitConverter.ToInt32(bytes, 0);
            Console.WriteLine($"byte -> int : {i}");

            byte[] bytes2 = BitConverter.GetBytes(2687511146);
            Console.WriteLine("int -> byte : " + BitConverter.ToString(bytes2));
        }
    }
}

 

기본 형식 데이터를 바이트로 변환하거나, 바이트를 기본 형식 데이터로 변환하고자 할 때는 BitConverter를 이용한다. BitConverter 메서드는 아주 많은 종류가 있다. 원하는 종류를 찾아 쓰면 된다.

 

https://docs.microsoft.com/ko-kr/dotnet/api/system.bitconverter?view=net-6.0 

 

BitConverter 클래스 (System)

기본 데이터 형식을 바이트의 배열로, 바이트의 배열을 기본 데이터 형식으로 변환합니다.

docs.microsoft.com

 

728x90