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.
我认为函数头应该类似于void ConvertMacToShort(char *macAddr, Short *shorts);
。我遇到的困难是解析 char*
。我觉得如果我循环它是可能的,但这感觉不够有效。我什至不需要将其设为某种通用函数 - MAC 地址始终是 01:23:45:67:89:ab 格式的
.char*
解析这个的好方法是什么?
最佳答案
效率是一回事……稳健性又是另一回事。
如果您有非常明确的情况,例如数百万个 MAC 地址的列表,这些地址都采用相同的格式(只有小写字母,总是前导零,...),那么我建议使用直接访问字符的快速函数.
如果您正在解析用户输入并且还需要检测输入错误,则不必担心执行速度。在这种情况下,您必须确保检测到用户能够犯的所有可能的错误(这是一项壮举)。这会导致 sscanf(..) ,在这种情况下,我什至建议编写自己的函数来解析字符串(根据我的经验 sscanf(..) 有时会导致麻烦取决于输入字符串,因此我在处理用户输入时避免使用它)。
另一件事:如果您担心执行时间的效率,请编写一个运行解析函数几百万次的小基准并比较执行时间。这很容易完成,有时还会带来惊喜......
关于c - 将 MAC 地址解析为三个 16 位短整型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34164565/