简体   繁体   中英

Parsing a MAC Address to an array of three 16-bit shorts

MAC Addresses are 48 bits. That is equivalent to three shorts. MAC addresses are sometimes written like this: 01:23:45:67:89:ab where each pair of digits represents a hexadecimal number.

Write a function that will take in a character pointer pointing to a null terminated string of characters like in the example and will break it apart and then store it in an array of three 16-bit shorts. The address of the array will also be passed into the function.

I figured the function header should look something like void convertMacToShort(char *macAddr, short *shorts); . What I'm having difficulty with is parsing the char* . I feel like it's possible if I loop over it, but that doesn't feel efficient enough. I don't even need to make this a universal function of sorts--the MAC address will always be a char* in the format of 01:23:45:67:89:ab .

What's a good way to go about parsing this?

Well efficiency is one thing ... robustness another.

If you have very defined circumstances like a list of millions of MAC addresses which are all in the same format (only lower case letters, always leading zeroes, ...) then I would suggest using a quick function accessing the characters directly.

If you're parsing user input and need to detect input errors as well, execution speed is not the thing to worry about. In this scenario you have to make sure that you detect all possible mistakes a user is able to do (and this is quite a feat). This leads to sscanf(..) and in that case I would even suggest to write your own function which parses the string (for my experience sscanf(..) sometimes causes trouble depending on the input string and therefore I avoid using it when processing user input).

Another thing: If you're worrying about efficiency in the means of execution time, write a little benchmark which runs the parsing function a few million times and compare execution time. This is easily done and sometimes brings up surprises...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM