C语言 如何将 MAC 地址(以字符串形式)转换为整数数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20553805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a MAC address (in string) to array of integers?
提问by Lior Avramov
How do I convert a MAC address within a string to an array of integers in C?
如何将字符串中的 MAC 地址转换为C 中的整数数组?
For example, I have the following string that stores a MAC address:
例如,我有以下存储 MAC 地址的字符串:
00:0d:3f:cd:02:5f
00:0d:3f:cd:02:5f
How do I convert this to:
我如何将其转换为:
uint8_t array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}
回答by TypeIA
uint8_t bytes[6];
int values[6];
int i;
if( 6 == sscanf( mac, "%x:%x:%x:%x:%x:%x%*c",
&values[0], &values[1], &values[2],
&values[3], &values[4], &values[5] ) )
{
/* convert to uint8_t */
for( i = 0; i < 6; ++i )
bytes[i] = (uint8_t) values[i];
}
else
{
/* invalid mac */
}
[EDIT: Added %cat the end of the format string to reject excess characters in the input, based on D Krueger's suggestion.]
[编辑:%c根据 D Krueger 的建议,在格式字符串的末尾添加以拒绝输入中的多余字符。]
回答by Tim Pierce
This is one of the few places where I'd consider using something like sscanf()to parse the string, since MAC addresses tend to be formatted very rigidly:
这是我考虑使用sscanf() 之类的东西来解析字符串的少数几个地方之一,因为 MAC 地址的格式往往非常严格:
char str[] = "00:0d:3f:cd:02:5f";
uint8_t mac_addr[6];
if (sscanf(str, "%x:%x:%x:%x:%x:%x",
&mac_addr[0],
&mac_addr[1],
&mac_addr[2],
&mac_addr[3],
&mac_addr[4],
&mac_addr[5]) < 6)
{
fprintf(stderr, "could not parse %s\n", str);
}

