C# - Byte Ordering


Server-Client 에서 TCP 통신을 하다 보면.. Byte Ordering 이 필요하다..
인텔 계열에서는 Little Endian을 사용하지만..
일반적으로 통신에서는 Big Endian을 사용하므로
Server와의 값을 주고 받을때 정수들은 Byte Ordering을 변환해 주어야 한다.
개념적으로 보면 아래와 같다.

사용자 삽입 이미지
이미지 출처 : http://blog.naver.com/fusdofls/50080412131

 
제가 사용하는 변환하는 소스는 아래와 같습니다.

public static void ConvertEndian(ref int pInt32Value)
{
    byte[] temp = BitConverter.GetBytes(pInt32Value);
    Array.Reverse(temp);
    pInt32Value = BitConverter.ToInt32(temp, 0);
}

public static void ConvertEndian(ref uint pUint32Value)
{
    byte[] temp = BitConverter.GetBytes(pUint32Value);
    Array.Reverse(temp);
    pUint32Value = BitConverter.ToUInt32(temp, 0);
}


public static void ConvertEndian(ref long pInt64Value)
{
    byte[] temp = BitConverter.GetBytes(pInt64Value);
    Array.Reverse(temp);
    pInt64Value = BitConverter.ToInt64(temp, 0);
}

public static void ConvertEndian(ref ulong pUint64Value)
{
    byte[] temp = BitConverter.GetBytes(pUint64Value);
    Array.Reverse(temp);
    pUint64Value = BitConverter.ToUInt64(temp, 0);
}

메소드 사용시 ref를 사용하세요..

ConvertEndian(ref numericData);

 

참고로 c#에서 Endianness를 확인하기 위해서는 아래를 참고시라..
BitConverter.IsLittleEndian

Endianness에 대해 자세한 사항은 아래의 위키피디아 참고..
http://en.wikipedia.org/wiki/Byte_ordering

광고

댓글 남기기