원문 : Convert integer to Byte Array in C#





Convert integer to Byte Array in C#




BitConverter 클래스를 이용하면 기본 데이터 타입(base data type) 을 바이트 배열(array of byte) 로 또는 그 반대로 변변환할 수 있다.




BitConverter 클래스는 정적 클래스(static class) 이며, Object를 바로 상속한 클래스 이다.

 

public static class BitConverter

cf) BitConverter class - MSDN


BitConverter 클래스는 오버로드된 정적인 메소드 GetBytes 메소드를 가지고 있다. GetBytes 메소드는 integer, double 또는 base data type 을 byte 배열로 변환시켜준다. 반대로 byte 배열을 base data type 을 변환시켜주는 정적 메소드(ToDouble, ToBoolean, ToChart, ToInt16, ToSingle) 를 가지고 있다.  

다음의 코드 조각은 여러 int data 를 byte 배열로 변환하는 방법을 보여준다.

namespace BitConverterSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Int and byte arrays conversion sample.");

            // Create double to a byte array
            Int32 i32 = 125;

            Console.WriteLine("Int value: " + i32.ToString());

            byte[] bytes = ConvertInt32ToByteArray(i32);

            Console.WriteLine("Byte array value:");
            Console.WriteLine(BitConverter.ToString(bytes))
    
        Console.WriteLine("Byte array back to Int32:");

            // Create byte array to Int32
            double dValue = ConvertByteArrayToInt32(bytes);

            Console.WriteLine(dValue.ToString());

            Console.ReadLine();
       }


       
public static byte[] ConvertInt32ToByteArray(Int32 I32)
        {
            return BitConverter.GetBytes(I32);
        }

        public static byte[] ConvertIntToByteArray(Int16 I16)
        {
            return BitConverter.GetBytes(I16);
        }

        public static byte[] ConvertIntToByteArray(Int64 I64)
        {
            return BitConverter.GetBytes(I64);
        }

        public static byte[] ConvertIntToByteArray(int I)
        {
            return BitConverter.GetBytes(I);
        }


        public static double ConvertByteArrayToInt32(byte[] b)
        {
            return BitConverter.ToInt32(b, 0);
        }
    }
}










Posted by six605
,