다음을 통해 공유


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

참고

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

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를 바이트 배열로 변환합니다.

참고

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

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

참고 항목

참조

BitConverter

IsLittleEndian

형식(C# 프로그래밍 가이드)