我有一个使用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]一样使用临时数组吗?
发布于 2014-07-12 02:33:42
为什么不使用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)。
https://stackoverflow.com/questions/24703875
复制相似问题