Server-Client 에서 TCP 통신을 하다 보면.. Byte Ordering 이 필요하다..
인텔 계열에서는 Little Endian을 사용하지만..
일반적으로 통신에서는 Big Endian을 사용하므로
Server와의 값을 주고 받을때 정수들은 Byte Ordering을 변환해 주어야 한다.
개념적으로 보면 아래와 같다.
이미지 출처 : http://blog.naver.com/fusdofls/50080412131
제가 사용하는 변환하는 소스는 아래와 같습니다.
01.
public
static
void
ConvertEndian(
ref
int
pInt32Value)
02.
{
03.
byte
[] temp = BitConverter.GetBytes(pInt32Value);
04.
Array.Reverse(temp);
05.
pInt32Value = BitConverter.ToInt32(temp, 0);
06.
}
07.
08.
public
static
void
ConvertEndian(
ref
uint
pUint32Value)
09.
{
10.
byte
[] temp = BitConverter.GetBytes(pUint32Value);
11.
Array.Reverse(temp);
12.
pUint32Value = BitConverter.ToUInt32(temp, 0);
13.
}
14.
15.
16.
public
static
void
ConvertEndian(
ref
long
pInt64Value)
17.
{
18.
byte
[] temp = BitConverter.GetBytes(pInt64Value);
19.
Array.Reverse(temp);
20.
pInt64Value = BitConverter.ToInt64(temp, 0);
21.
}
22.
23.
public
static
void
ConvertEndian(
ref
ulong
pUint64Value)
24.
{
25.
byte
[] temp = BitConverter.GetBytes(pUint64Value);
26.
Array.Reverse(temp);
27.
pUint64Value = BitConverter.ToUInt64(temp, 0);
28.
}
1.
ConvertEndian(
ref
numericData);
참고로 c#에서 Endianness를 확인하기 위해서는 아래를 참고시라..
BitConverter.IsLittleEndian자료 출처 : http://kimstar.pe.kr/blog/226
그리고 C# String <==> Byte []
private static byte[] StrtoByteArray(string recvStr, bool reverse)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] rtnValue = encoding.GetBytes(recvStr);
if (reverse)
Array.Reverse(rtnValue);
return rtnValue;
}
private static string ByteArraytoStr(byte [] byteArray, bool reverse)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
if (reverse)
Array.Reverse(byteArray);
string rtnValue = encoding.GetString(byteArray);
return rtnValue;
}