c - 将 MAC 地址解析为三个 16 位短整型数组

标签 c string-parsing short bit-packing

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/

相关文章:

java - 从视频帧中检索时间码

在没有分支的情况下在 CUDA 中进行比较

java - Sax解析器不完全读取一行

java - 何时在程序中使用短、字节和十六进制基本类型?

c - Short to Char 类型转换

c# - 8 位和 16 位整数的算术运算

c - 使用 vfork() 对子级数求和

c - 为什么我得到这个元素的内存地址?

c# - C# 中带有非捕获组的正则表达式

c++ - 将字符串转换为整数数组