我想从命令行获取MAC地址,所以我把它作为字符串...如何将这个17字节的MAC字符串转换为“00:0d:3f:cd:02:5f”到C中的6字节MAC地址
On a C99-conformant implementation, this should work
unsigned char mac[6];
sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
Otherwise, you'll need:
unsigned int iMac[6];
unsigned char mac[6];
int i;
sscanf(macStr, "%x:%x:%x:%x:%x:%x", &iMac[0], &iMac[1], &iMac[2], &iMac[3], &iMac[4], &iMac[5]);
for(i=0;i<6;i++)
mac[i] = (unsigned char)iMac[i];
Without built-in functions and error handling simply:
unsigned char mac[6];
for( uint idx = 0; idx < sizeof(mac)/sizeof(mac[0]); ++idx )
{
mac[idx] = hex_digit( mac_str[ 3 * idx ] ) << 4;
mac[idx] |= hex_digit( mac_str[ 1 + 3 * idx ] );
}
Input is actually 3*6 bytes with \\0
.
unsigned char hex_digit( char ch )
{
if( ( '0' <= ch ) && ( ch <= '9' ) ) { ch -= '0'; }
else
{
if( ( 'a' <= ch ) && ( ch <= 'f' ) ) { ch += 10 - 'a'; }
else
{
if( ( 'A' <= ch ) && ( ch <= 'F' ) ) { ch += 10 - 'A'; }
else { ch = 16; }
}
}
return ch;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.