gpt4 book ai didi

c - 解析 mac 地址和移动 temp 时检查 strtol() 时出错。指针向上

转载 作者:行者123 更新时间:2023-11-30 15:31:35 26 4
gpt4 key购买 nike

我有一个函数,可以使用 strtol() 将 MAC 地址从 00:11:22:33:44:55 格式转换为 6 字节数组。现在我的函数基本上工作正常,但我想知道如何在第一次转换之后进行正确的错误检查。到目前为止,我的代码如下所示:

char* pEnd = NULL;
errno = 0;
// wanmac shall be formatted like: "00:11:22:33:44:55"
// Check for valid index into switch_wan_macs array
if (idx<0 || idx> MAX_WAN_PORTS){
return BCM_E_FAIL;
}
// set wan_mac
//interpret the 6 bytes of the mac with base 16 (hex) while omitting the colons (move next pointer up by 1)
switch_wan_macs[idx].wan_mac[0] = strtol (wan_mac, &pEnd, 16);
if (pEnd == wan_man || errno == ERANGE) {
printf("Conversion of MAC string %s failed\n", wan_mac);
return BCM_E_FAIL;
}
switch_wan_macs[idx].wan_mac[1] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[2] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[3] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[4] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[5] = strtol (pEnd+1, NULL, 16);

return BCM_E_NONE;

并且我确实可以在任何后续步骤中将剩余字符串转换为原始字符串。我最好使用 char pEnd[6] 那样的临时数组吗?

最佳答案

为什么不使用sscanf

#include <stdio.h>

int main() {
char mac[20] = "00:11:22:33:44:55";
unsigned a[6];

if (6 != sscanf(mac, "%2x:%2x:%2x:%2x:%2x:%2x",
a, a+1, a+2, a+3, a+4, a+5)) {
fprintf(stderr, "Error in mac string\n");
return 1;
}

printf("%.2x %.2x %.2x %.2x %.2x %.2x\n",
a[0], a[1], a[2], a[3], a[4], a[5]);

return 0;
}

顺便说一句,您的有效 idx 检查可能应该是 idx>=MAX_WAN_PORTS (如果您将 switch_wan_macs 定义为具有大小 MAX_WAN_PORTS)。

关于c - 解析 mac 地址和移动 temp 时检查 strtol() 时出错。指针向上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703875/

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