0

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

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]吗?

4

1 回答 1

1

为什么不使用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为 size MAX_WAN_PORTS)。

于 2014-07-11T18:33:41.660 回答