Share a byte sequence knowledge
This problem occurs during project communication. The length and type of the packet are determined as the big end (Network byte order) in the transmission medium ), however, the data read after the conversion is displayed as small-end (host byte order) data. The specific process is described below, so that you can easily understand the data distribution, Data Reading, and big-end and small-end issues in the memory.
Package Type
Typedef struct {
Unsigned short packet_len;
Unsigned short packet_type;
Message task; // Google protoco buffer, no need to care about the internal details
} Task;
The environment is windows and Intel processors, so the data distribution in the memory is small by default.
At the beginning, we will perform htons on packet_len and packet_type to convert it to the network byte order (that is, the big end), and then use it for network transmission.
When parsing, the data we obtain is displayed as a small terminal. After finding the cause, we find that, the data written and read in our own database functions write_int and read_int will change the byte order. In fact, ntohs and htons functions are provided.
The specific behavior is as follows:
Packet_len = 15
The hexadecimal value is 0x000f, and the value in the memory is 0f 00, which is due to the low position.
To change it from the host's byte order to the network's byte order, we can use htons, after calling Big = htons (packet_len)
The hexadecimal value of big is 0x0f00, and the value in memory is 00 0f.
After we convert to the network byte sequence and obtain some column data, we need to write it into the buffer, and control the Protocol by sending and receiving the buffer.
Write_int is used to write data to the buffer. The function is to write data to the buffer in bytes in sequence.
Then packet_len writes the buffer after being converted to the byte sequence of the network, and takes the first two bytes for analysis (packet_len)
The first byte is 0x0f.
The second byte is: 0x00.
At this time, we can see that the packet_len we actually transmitted has changed to 0x0f00 in the buffer, so the low position of the sub-terminal is the first, the read data is actually a small-end data of 0x000f. Therefore, we cancel calling htons for packet_len and packet_type.
Appendix: write_int Function
Template <class T>
T write_int (int cb/* length of the buffer to be written */, t W0/* pointer to the buffer */, long V/* data to be written */)
{
Unsigned char * w = reinterpret_cast <unsigned char *> (w0 );
W + = CB;
For (INT I = 0; I <CB; I ++)
{
* -- W = V & 0xff;
V >>> = 8;
}
Return reinterpret_cast <t> (W + CB );
}