「6F:e:5B:7C:b:a」のような MAC アドレスを解析して、:e:、:b:、:a の前に暗黙のゼロを挿入します。
現時点では Boost を使用できませんが、大まかな解決策があります。ソリューションは「:」で分割されます。次に、その間の文字を数え、1 つしかない場合は先頭にゼロを挿入します。
誰かがより速いアプローチを持っているかどうか疑問に思っていましたか?
「6F:e:5B:7C:b:a」のような MAC アドレスを解析して、:e:、:b:、:a の前に暗黙のゼロを挿入します。
現時点では Boost を使用できませんが、大まかな解決策があります。ソリューションは「:」で分割されます。次に、その間の文字を数え、1 つしかない場合は先頭にゼロを挿入します。
誰かがより速いアプローチを持っているかどうか疑問に思っていましたか?
迅速で汚い場合:
if (sscanf(text, "%x:%x:%x:%x:%x:%x",
&mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
// handle error
}
数値が本当に 16 進数かどうかはチェックしないことに注意してください。sscanf() の通常の予防措置が適用されます。
まず、非常に高速に変換char
するスクリプトを使用できます。int
unsigned char hex_to_int(const char c)
{
if( c >= 'a' && c <= 'f'){
return c - 'a' + 10;
}
if( c >= 'A' && c <= 'F'){
return c - 'A' + 10;
}
if( c >= '0' && c <= '9'){
return c - '0';
}
return 0;
}
次に、文字列を反復するループを作成できます。
unsigned char mac[6]; /* Resulting mac */
int i; /* Iteration number */
char *buffer; /* Text input - will be changed! */
unsigned char tmp; /* Iteration variable */
for( i = 0; i < 6; ++i){
mac[i] = 0;
/*
* Next separator or end of string
* You may also want to limit this loop to just 2 iterations
*/
while( ((*buffer) != '\0') && ((*buffer) != ':'){
mac[i] <<= 4;
mac[i] |= hex_to_int( *buffer);
++buffer;
}
}
if( (i != 6) || (*buffer != NULL)){
// Error in parsing, failed to get to the 6th iteration
// or having trailing characters at the end of MAC
}
この関数はエラー チェックを行いませんが、おそらく最速のソリューションです。