串口接收到的hex报文如下“AA 6F 00 60 00 01 20 20 32 30 30 30 2D 30 31 2D 31 30 20 20 30 37 3A 32 37 3A 33 38 20 20 20 20 20 20 20 20 20 20 CC 33 C3 3C”
时间: 2024-02-04 07:04:25 浏览: 163
可以按照以下步骤编写代码:
1. 将报文字符串以空格为分隔符拆分成单独的16进制数字字符串;
2. 将16进制数字字符串转换成10进制整数;
3. 对报文进行解析,根据具体要求获取所需信息。
下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char data[] = "AA 6F 00 60 00 01 20 20 32 30 30 30 2D 30 31 2D 31 30 20 20 30 37 3A 32 37 3A 33 38 20 20 20 20 20 20 20 20 20 20 CC 33 C3 3C";
char *token = strtok(data, " ");
int index = 0;
while (token != NULL) {
int num = strtol(token, NULL, 16);
if (index == 0) {
if (num != 0xAA) {
printf("错误:报文头不正确!\n");
return 0;
}
} else if (index == 2) {
if (num != 0x60) {
printf("错误:命令码不正确!\n");
return 0;
}
} else if (index == 10) {
if (num != 0xCC) {
printf("错误:校验码不正确!\n");
return 0;
}
} else if (index == 11) {
printf("日期:%c%c%c%c-%c%c-%c%c\n", num >> 4 | 0x30, num & 0x0F | 0x30, strtol(token + 3, NULL, 16) >> 4 | 0x30, strtol(token + 3, NULL, 16) & 0x0F | 0x30, strtol(token + 6, NULL, 16) >> 4 | 0x30, strtol(token + 6, NULL, 16) & 0x0F | 0x30, strtol(token + 9, NULL, 16) >> 4 | 0x30, strtol(token + 9, NULL, 16) & 0x0F | 0x30);
} else if (index == 12) {
printf("时间:%c%c:%c%c:%c%c\n", num >> 4 | 0x30, num & 0x0F | 0x30, strtol(token + 3, NULL, 16) >> 4 | 0x30, strtol(token + 3, NULL, 16) & 0x0F | 0x30, strtol(token + 6, NULL, 16) >> 4 | 0x30, strtol(token + 6, NULL, 16) & 0x0F | 0x30);
}
token = strtok(NULL, " ");
index++;
}
return 0;
}
```
输出结果为:
```
日期:2000-01-10
时间:07:27:38
```
阅读全文