gpt4 book ai didi

c - 使用 sscanf 验证十六进制格式的命令字符串

转载 作者:行者123 更新时间:2023-11-30 14:59:50 24 4
gpt4 key购买 nike

我将收到格式为“%04hx %04hx”的命令参数字符串。示例命令参数字符串为“09EC 000A”。

我需要检查数据格式是否有效。我尝试使用以下格式字符串检查参数字符串是否有效

“%[0123456789abcdefABCDEF]s”。即使十六进制数字之间存在多个空格并且存在前导空格,此格式也将有效。

是否可以使用sscanf检查命令参数字符串是否只有两个4位十六进制数字,并且它们之间有空格?

马努

最佳答案

Is it possible to check whether the command parameter string has only two 4 digit hexadecimal numbers with a space between them with sscanf?

是的,检查每个字符并用“%n”保存扫描的字符数。

  // notice no 's' at the end
#define HEX1 "%*1[0123456789abcdefABCDEF]"
// the '*' directs sscanf() to not save the result.
#define SPC1 "%*1[ ]"

char *sample = "09EC 000A";
int n = 0;
sscanf(sample, HEX1 HEX1 HEX1 HEX1 SPC1 HEX1 HEX1 HEX1 HEX1 "%n", &n);
if (n && sample[n] == 0) {
puts("Success");
} else {
puts("Fail");
}

或者可以使用sscanf()的返回值并用哨兵检测尾随字符。

  char hex[2][5] = { 0 };
char sentinel;
#define HEX "%1[0123456789abcdefABCDEF]"
//#define SPC1 "%*1[ ]"
if (8 == sscanf(sample, HEX HEX HEX HEX SPC1 HEX HEX HEX HEX "%c",
&hex[0][0], &hex[0][1], &hex[0][2], &hex[0][3],
&hex[1][0], &hex[1][1], &hex[1][2], &hex[1][3],
&sentinel)) {
printf("Success %s %s\n", hex[0], hex[1]);
} else {
puts("Fail");
}

或者可能是不太冗长的内容

  #define HEX4 "%4[0123456789abcdefABCDEF]"
sscanf(sample, HEX4 SPC1 HEX4 "%n", hex[0], hex[1], &n);
if (n == 9 && sample[n] == 0) {
printf("Success %s %s\n", hex[0], hex[1]);
} else {
puts("Fail");
}

直接使用“%x”允许选择前导空白字符。可以使用"%n"来检测。然而 "%x" 允许 "0x12""+123""-123",即以下内容不无效。

  int m[4] = { 0 };
unsigned cmd[2];
sscanf(sample, " %n%x%n" SPC1 " %n%x%n",
&m[0], &cmd[0], &m[1],
&m[2], &cmd[1], &m[3]);
if (m[0] == 0 && m[1] == 4 && m[2] == 5 && m[3] == 9 && sample[m[3]] == 0) {
printf("Success %04x %04x\n", cmd[0], cmd[1]);
} else {
puts("Fail");
}

许多可能性。

关于c - 使用 sscanf 验证十六进制格式的命令字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com