将MAC地址std :: string转换为uint64_t

Joh*_*0te 8 c++ unix

我有一个十六进制MAC地址保存在std :: string中.将该MAC地址转换为uint64_t中保存的整数类型的最佳方法是什么?

我知道stringstream,sprintf,atoi等.我实际上用前两个编写了很少的转换函数,但它们似乎比我想要的更加草率.

所以,有人能告诉我一个好的,干净的转换方式

std::string mac = "00:00:12:24:36:4f";
Run Code Online (Sandbox Code Playgroud)

进入uint64_t?

PS:我没有可用的boost/TR1设施,并且无法在实际使用代码的地方安装它们(这也是为什么我没有复制粘贴我的尝试之一,抱歉!).所以请保留直接C/C++调用的解决方案.如果您有一个有趣的UNIX系统调用解决方案,我也会感兴趣!

Max*_*kin 9

uint64_t string_to_mac(std::string const& s) {
    unsigned char a[6];
    int last = -1;
    int rc = sscanf(s.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx%n",
                    a + 0, a + 1, a + 2, a + 3, a + 4, a + 5,
                    &last);
    if(rc != 6 || s.size() != last)
        throw std::runtime_error("invalid mac address format " + s);
    return
        uint64_t(a[0]) << 40 |
        uint64_t(a[1]) << 32 | ( 
            // 32-bit instructions take fewer bytes on x86, so use them as much as possible.
            uint32_t(a[2]) << 24 | 
            uint32_t(a[3]) << 16 |
            uint32_t(a[4]) << 8 |
            uint32_t(a[5])
        );
}
Run Code Online (Sandbox Code Playgroud)


AB7*_*1E5 5

我的解决方案(需要c ++ 11):

#include <string>
#include <cstdint>
#include <algorithm>
#include <stdlib.h>


uint64_t convert_mac(std::string mac) {
  // Remove colons
  mac.erase(std::remove(mac.begin(), mac.end(), ':'), mac.end());

  // Convert to uint64_t
  return strtoul(mac.c_str(), NULL, 16);
}
Run Code Online (Sandbox Code Playgroud)