c# - Byte Ordering


일반적으로 network 통신에서 사용하는 정수형은 Big Endien을 사용합니다.
Windows 계열은 Little Endien이므로 Byte 순서를 변경하여 읽거나 써야 합니다.

IntToBytesBigEndien 메소드는 정수형을 network stream 으로 전송하기 위해 byte 배열로 변환해 줍니다.
주석 처리된 method #1, #2도 동일하게 동작합니다.

BytesBigEndianToInt 메소드는 network stream으로 수신한 byte 배열을 정수형으로 변환합니다.

/// <summary>
/// int값을 빅인디언 형태의 byte[4]로 반환합니다.
/// </summary>
/// <param name="intValue">변환할 Int32</param>
/// <returns>빅인디언 형태의 byte[4]</returns>
public static byte[] IntToBytesBigEndien(int intValue)
{
    // 참고 : http://stackoverflow.com/questions/1318933/c-sharp-int-to-byte
    // ------ method #1 ------
    //byte[] bytes = BitConverter.GetBytes(intValue);
    //Array.Reverse(bytes);
    //return bytes;

    // ------ method #2 ------ 
    //return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(intValue));

    // ------ method #3 ------
    byte[] bytes = new byte[4];
    bytes[0] = (byte)(intValue >> 24);
    bytes[1] = (byte)(intValue >> 16);
    bytes[2] = (byte)(intValue >> 8);
    bytes[3] = (byte)intValue;
    return bytes;
}

/// <summary>
/// 빅인디언인 byte[]을 정수형으로 변환합니다.
/// </summary>
/// <param name="bytes">byte[]이며, 길이는 1,2,4만 지원합니다.</param>
/// <returns>정수형 값</returns>
internal static int BytesBigEndianToInt(byte[] bytes)
{
    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);

    int rtn = 0;
    switch(bytes.Length)
    {
        case 1 : rtn = (int)bytes[0]; break;
        case 2 : rtn = BitConverter.ToInt16(bytes, 0); break;
        case 4 : rtn = BitConverter.ToInt32(bytes, 0); break;
    }

    return rtn;
}

 

광고

2개의 댓글

댓글 남기기