如何將字符串中的MAC地址轉換爲整數數組C?如何將MAC地址(字符串)轉換爲整數數組?
例如,我有一個存儲MAC地址以下字符串:
00:0D:3F:CD:02:5F
如何將它轉換爲:
uint8_t array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}
如何將字符串中的MAC地址轉換爲整數數組C?如何將MAC地址(字符串)轉換爲整數數組?
例如,我有一個存儲MAC地址以下字符串:
00:0D:3F:CD:02:5F
如何將它轉換爲:
uint8_t array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}
這是我考慮使用類似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);
}
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 */
}
[編輯:在格式字符串的末尾添加%c
輸入拒絕多餘的字符,基於d克魯格的建議]
並不安全,並且將生成警告在某些編譯器中,因爲你傳遞了指向'uint8_t'的指針,這幾乎肯定不像'sscanf()'期望的'int'寬。 – TypeIA
好的,夠公平的。 –