TCPSendRecv - 8BitsCoding/RobotMentor GitHub Wiki
Intel CPU ๊ณ์ด์์ ์ฌ์ฉ๋จ
๋ฐ์ดํฐ : 0x01 02 03 04 ๋ผ๋ฉด
๋ฉ๋ชจ๋ฆฌ : 04 03 02 01 ์ผ๋ก ์ ์ฅ์ด๋๋ค.
ํ ๋ง๋๋ก
์ฃผ์ 3๋ฒ | ์ฃผ์ 2๋ฒ | ์ฃผ์ 1๋ฒ | ์ฃผ์ 0๋ฒ |
04 | 03 | 02 | 01
Network์์ ์ฌ์ฉ๋๋ ์๋์ธ
๋ฐ์ดํฐ : 0x01 02 03 04
๋ฉ๋ชจ๋ฆฌ : 01 02 03 04
์ฃผ์ 0๋ฒ | ์ฃผ์ 1๋ฒ | ์ฃผ์ 2๋ฒ | ์ฃผ์ 3๋ฒ |
01 | 02 | 03 | 04
Example2 ๋ง ๋ณด๋ฉด๋จ.
App1.
๋ฐ์ดํฐ : 0x01 02 03 04
๋ฉ๋ชจ๋ฆฌ : 04 03 02 01
<๋คํธ์ํฌ๋ก ์ก์ >
Net.
01 02 03 04
<๋คํธ์ํฌ๋ก ์ก์ >
App2.
์ฃผ์๊ฐ 04 | ์ฃผ์๊ฐ 03 | ์ฃผ์๊ฐ 02 | ์ฃผ์๊ฐ 01
๋ฉ๋ชจ๋ฆฌ : 01 02 03 04 (์ด๋ ๊ฒ ์ฝ์ด์ค๋ ์ด์ ? Net.์ Big Endian 04 -> 03 -> 02 -> 01 ์์ผ๋ก ๋ณด๋ด๊ณ App2๋ Little Endian์ผ๋ก ์ฃผ์๊ฐ 01 -> 02 -> 03 -> 04 ์์ผ๋ก ์ ์ฅ๋๋ค.)
๋ฐ์ดํฐ : 04 03 02 01
ํด๊ฒฐ๋ฐฉ๋ฒ์ด ์ด๋ ค๊ฐ์ ์๋ํ ๋ชจ๋ ์ค๋ช
App1.
๋ฐ์ดํฐ : 0x12 34 56 78
<๋ฉ๋ชจ๋ฆฌ ์ค์> (๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ค์ํ๋ ์ด์ ๋ ์ฌ๋ฌ๊ฐ์ง๊ฐ ์๊ฒ ์ง๋ง ๋คํธ์ํฌ์์ ๋ณด๊ธฐ ์ข๊ฒ(์ํ๋ ๋ฉ๋ชจ๋ฆฌํํ๋ก) ํ๊ธฐ ์ํด์๊ฐ ๊ฐ์ฅํฌ๋ค.)
๋ฉ๋ชจ๋ฆฌ : 78 56 34 12
<๋คํธ์ํฌ๋ก ์ก์ >
Net.
12 34 56 78
<๋คํธ์ํฌ๋ก ์ก์ >
App2.
App2์์ ์์ ํ๋ ๋ฐฉ๋ฒ์ด ๋ ๊ฐ์ง์ด๋ค.
๋ฐฉ๋ฒ1 - memcpy
๋ฉ๋ชจ๋ฆฌ : 04 03 02 01
๋ฐ์ดํฐ : 01 02 03 04
App2.
์์ด์ด ์คํฌ์์ TCP ํต์ ์์ฐ์ด๋ณธ ๊ทธ๋ฆผ
๋ณด๋ด๋ ์ชฝ์์๋ ์ด๋ป๊ฒ ๋ณด๋๋์ง ํ์ธํด๋ณด์.
_message.RBitResultReportSwap.nresult = 1;
_message.RBitResultReportSwap.MessageHeader.uiMsgID = 0x03002010;
_message.RBitResultReportSwap.MessageHeader.uiMsgCount = 0;
_message.RBitResultReportSwap.MessageHeader.uiMsgLength = sizeof(_message.RBitResultReportSwap) - sizeof(_message.RBitResultReportSwap.MessageHeader);
_message.RBitResultReportSwap.MessageHeader.uiMsgCount = _message.SWap32(_message.RBitResultReportSwap.MessageHeader.uiMsgCount);
_message.RBitResultReportSwap.MessageHeader.uiMsgLength = _message.SWap32(_message.RBitResultReportSwap.MessageHeader.uiMsgLength);
_message.RBitResultReportSwap.nresult = _message.SWap32(_message.RBitResultReportSwap.nresult);
write(sockfd,(char *)&_message.RBitResultReportSwap,sizeof(_message.RBitResultReportSwap));
0xff ff ff ff ๋ ๋ช ๋ฐ์ดํธ์ผ๊น?
8bit๊ฐ 1byte์์ ์๋ค
f = 1111 = 4bits์ด๊ณ
ff = 1111 1111 = 8bits = 1bytes์ด๋ค.
๋ฐ๋ผ์
0xff ff ff ff = 4bytes์ด๋ค.
#define CH_2BYTE(type) SwapTwoByte((unsigned char *)&type, (unsigned char *)&type)
#define CH_4BYTE(type) SwapFourByte((unsigned char *)&type, (unsigned char *)&type)
#define CH_8BYTE(type) SwapEightByte((unsigned char *)&type, (unsigned char *)&type)
template <class type>
void SwapThreeByte(type *source, type *dest)
{
unsigned char temp[3];
temp[0] = source[2];
temp[1] = source[1];
temp[2] = source[0];
memcpy(dest, temp, 3);
}
template <class type>
void SwapTwoByte(type *source, type *dest)
{
unsigned char temp[2];
temp[0] = source[1];
temp[1] = source[0];
memcpy(dest, temp, 2);
}
template <class type>
void SwapBytes(type *source, int length)
{
unsigned char temp;
for ( int i=0; i<length; i+=2)
{
temp = source[i];
source[i] = source[i+1];
source[i+1] = temp;
}
}