다음을 통해 공유


바이트 배열을 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)의 두 번째 인수는 바이트 배열의 시작 인덱스를 지정합니다.

비고

출력은 컴퓨터 아키텍처의 엔디언에 따라 다를 수 있습니다.

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: {i}");
// Output: int: 25

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

비고

출력은 컴퓨터 아키텍처의 엔디언에 따라 다를 수 있습니다.

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

참고하십시오