바이트 배열을 int로 변환하는 방법(C# 프로그래밍 가이드)

이 예제에서는 BitConverter 클래스를 사용하여 바이트 배열을 int로 변환하고 다시 바이트 배열로 변환하는 방법을 보여 줍니다. 예를 들어 네트워크에 바이트를 읽은 후 바이트에서 기본 제공 데이터 형식으로 변환해야 할 수 있습니다. 예제의 ToInt32(Byte[], Int32) 메서드 외에도 다음 표에서는 바이트(바이트 배열)를 다른 기본 제공 형식으로 변환하는 BitConverter 클래스의 메서드를 보여 줍니다.

반환되는 형식 메서드
bool ToBoolean(Byte[], Int32)
char ToChar(Byte[], Int32)
double ToDouble(Byte[], Int32)
short ToInt16(Byte[], Int32)
int ToInt32(Byte[], Int32)
long ToInt64(Byte[], Int32)
float ToSingle(Byte[], Int32)
ushort ToUInt16(Byte[], Int32)
uint ToUInt32(Byte[], Int32)
ulong ToUInt64(Byte[], Int32)

예제

이 예제에서는 바이트 배열을 초기화하고, 컴퓨터 아키텍처가 little-endian이면 배열을 반전한 다음(즉, 최하위 바이트가 먼저 저장됨) ToInt32(Byte[], Int32) 메서드를 호출하여 배열의 4바이트를 int로 변환합니다. ToInt32(Byte[], Int32)에 대한 두 번째 인수는 바이트 배열의 시작 인덱스를 지정합니다.

참고 항목

출력은 컴퓨터 아키텍처의 endianness에 따라 달라질 수 있습니다.

byte[] bytes = [0, 0, 0, 25];

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25

이 예제에서는 BitConverter 클래스의 GetBytes(Int32) 메서드를 호출하여 int를 바이트 배열로 변환합니다.

참고 항목

출력은 컴퓨터 아키텍처의 endianness에 따라 달라질 수 있습니다.

byte[] bytes = BitConverter.GetBytes(201805978);
Console.WriteLine("byte array: " + BitConverter.ToString(bytes));
// Output: byte array: 9A-50-07-0C

참고 항목