C++ escape character-solve the annoying protocol header and end hexadecimal problem

definition

Escape character is a special form of character in C language. Usually, escape characters are used to represent non-printable control characters and characters with specific functions in the ASCII character set.

Example

Common escape characters and corresponding ASCII codes
\a Bell (BEL)
\b Backspace (BS)
\f Form feed (FF)
\n Line feed (LF)
\r Carriage return (CR)
\t Horizontal Tab (HT)
\ v Vertical Tab (VT)
\\ Backslash \
\0 Null character (NULL), often used as the end of a string
\ddd Any character, up to three octal digits
\ xhh Any character, up to two hexadecimal digits

Application scenarios

  • Network protocol

In the network protocol, there will be a frame header and a frame tail, which are used to define a complete frame to solve the phenomenon of packet sticking.

For example, the following simple protocol format:

Start code Data length Data content Check code End code
0xCD 0xCD 0x00 0x3D (String) 0xED 0x70 0x3A 0x4D

If we want to send a complete data frame to the network, we first need the appropriate data content, and then encapsulate the data content-add start code and end code, calculate data length, check code, only the frame format meets the format specified in the protocol, Only allow it to send.

However, many times, we will find that it is not easy to add the start code and end code to the frame (store all data in the form of a string). How to easily convert a hexadecimal number into a string? There are several methods:

  1. The hexadecimal number of each byte is sequentially converted into a character type, and then assigned to the corresponding index position of the frame string one by one.
  2. Directly convert the entire hexadecimal number into a string form, and then append it to the frame string.

For method 1, it can be implemented like this:

//存储完整一帧数据
char data[256];
//定义char变量,并以16进制数为其赋值
//添加起始码
char c = 0xCD;
data[0] = c;
data[1] = c;
//添加结束码
c = 0x3A;
data[254] = c;
c = 0x4D;
data[255] = c;

It can be seen that the assignment of each digit requires 2 lines of code, which is quite troublesome, especially when there are a lot of such numbers.

Let's look at the implementation of Method 2:

//存储完整一帧数据
char data[256];
//定义char *变量,并以字符串为其赋值
//添加起始码
char *str = "\xCD\xCD";    //注意转义字符的使用,\xhh表示十六进制数字
strcpy(data, str);
//添加结束码
str = "\x3A\x4D";
strcpy(data+254, str);

By comparison, it is found that Method 2 is more concise, readable and easy to understand than Method 1.

When there are a lot of numbers to be converted, using Method 2 will significantly improve the conversion efficiency!

Guess you like

Origin blog.csdn.net/gkzscs/article/details/83658760