Socket or serial port print message

When using socket or serial communication, when we print message information, we encounter the situation of printing garbled characters:

1. Store the message array:

unsigned char send[100];

2. Message information:

uint16_t  head = 0xAA01;

head = htons(head);

memcpy(send,&head,sizeof(uint16_t));

uint16_t  length = 0x1234;

length = htons(length);

memcpy(send+2,&length,sizeof(uint16_t));

3. Print message

printf("%s",send); //Wrong printing method, what is printed out is garbled, because what we write into the message is a hexadecimal number, and it should be read in hexadecimal format when reading Out each byte.

for(int i =0;i<4;i++) //correct printing method

      printf("%02x ",send[i]);

4. Summary

It must be remembered: integer variables and character variables are not separated, and the two can be converted into each other;

Type the written hexadecimal integer type as a character type, and print the character whose hexadecimal number is the ASCII code, so it may be garbled;

Therefore, to print out the written hexadecimal number as it is, you need to use %x ( %02x meaning: the printed hexadecimal number is two digits, and 0 is added to the left of less than two digits );

 

 

 

Guess you like

Origin blog.csdn.net/modi000/article/details/112553919