我有一个像这样的十六进制字符串 00133587a1bddb8dae00a3a01a010100
,它实际上是 7 个十六进制字符串连接在一起,展开后看起来像这样 00 133587a1 bddb8dae 00a3a01a 01 01 00
。我正在尝试将这些值中的前 5 个扫描到这个结构中
typedef struct __param_value{
uint8_t sytem_id;
uint8_t comp_id;
uint16_t seq;
uint8_t frame;
uint16_t command;
uint8_t current;
uint8_t autocontinue;
float param1;
float param2;
float param3;
float param4;
float x;//param7
float y;//param8
float z;//param9
uint8_t fwt;
}param_value
最后2个进入这些变量
int txtseq;
int cont=1;
像这样使用sscanf
sscanf(in_str,"%2x%8x%8x%8x%2x%2x%2x",&(points[wp].seq),&(points[wp].x),&(points[wp].y),&(points[wp].z),&(points[wp].fwt),&txtseq,&cont);
但我想不出正确的语法。可以这样做吗?
最佳答案
您必须传递 unsigned int
的地址以扫描 %x
格式说明符的数据。然后您可以转换为正确的数据类型。
#include <stdio.h>
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef struct param_value{
uint8_t sytem_id;
uint8_t comp_id;
uint16_t seq;
uint8_t frame;
uint16_t command;
uint8_t current;
uint8_t autocontinue;
float param1;
float param2;
float param3;
float param4;
float x;//param7
float y;//param8
float z;//param9
uint8_t fwt;
}param_value;
int main(void) {
char hexstr [] = "00133587a1bddb8dae00a3a01a010100";
unsigned v1, v2, v3, v4, v5, v6, v7;
param_value rec;
int txtseq;
int cont;
if (7 != sscanf(hexstr, "%2x%8x%8x%8x%2x%2x%2x", &v1, &v2, &v3, &v4, &v5, &v6, &v7))
{
printf ("Bad scan\n");
return 1;
}
rec.seq = (uint16_t)v1;
rec.x = (float)v2;
rec.y = (float)v3;
rec.z = (float)v4;
rec.fwt = (uint8_t)v5;
txtseq = (int)v6;
cont = (int)v7;
printf("%u %f %f %f %u %d %d\n", rec.seq, rec.x, rec.y, rec.z,
rec.fwt, txtseq, cont);
return 0;
}
程序输出:
0 322275232.000000 3185282560.000000 10723354.000000 1 1 0
但是:您没有提到 y
值 bddb8dae
是否为负数。
关于c - 十六进制字符串的扫描值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30887759/