我想将格式为00:11:22:33:44:55
的mac字符串解释为6个二进制字节,即0x00,0x11,0x22,0x33,0x44,0x55。
我已尝试使用以下代码完成此操作:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main (void)
{
char mac[16]={0};
char binmac[8]={0};
char* pEnd;
strcpy(mac,"00:11:22:33:44:55");
printf("mac %s\n", mac);
binmac[0] = strtol (mac, &pEnd, 16);
binmac[1] = strtol (pEnd+1, &pEnd, 16);
binmac[2] = strtol (pEnd+1, &pEnd, 16);
binmac[3] = strtol (pEnd+1, &pEnd, 16);
binmac[4] = strtol (pEnd+1, &pEnd, 16);
binmac[5] = strtol (pEnd+1, NULL, 16);
printf ("binmac 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",binmac[0], binmac[1], binmac[2], binmac[3], binmac[4], binmac[5]);
}
但我得到的结果看起来并不正确:
mac 00:11:22:33:44:55
binmac 0x00 0x11 0x22 0x33 0x44 0x05
我想知道为什么最后一个字节没有被正确解释。 感谢
答案 0 :(得分:2)
这可以通过更简单的方式完成。看起来评论者已经发现了你的错误。
代码清单
#define MAC_LENGTH (6)
#include <stdio.h>
int main(void) {
const char* macStr = "00:11:22:33:44:55";
int i;
unsigned char mac[MAC_LENGTH];
sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
printf("Original String:%s\n", macStr);
printf("Parsed String:\n");
for (i=0; i<MAC_LENGTH; i++) {
printf(" mac[%d] = 0x%02X\n", i, mac[i]);
}
return 0;
}
示例运行
Original String:00:11:22:33:44:55
Parsed String:
mac[0] = 0x00
mac[1] = 0x11
mac[2] = 0x22
mac[3] = 0x33
mac[4] = 0x44
mac[5] = 0x55
<强>参考强>
<https://stackoverflow.com/questions/12772685/how-to-convert-mac-string-to-a-byte-address-in-c>