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

新手上路,请多包涵

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

我知道 stringstream、sprintf、atoi 等。我实际上用前 2 个函数编写了一些转换函数,但它们似乎比我想要的更草率。

那么,有人可以告诉我一个好的,干净的转换方式吗

std::string mac = "00:00:12:24:36:4f";

变成 uint64_t?

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

原文由 John Humphreys 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答
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])
        );
}

原文由 Maxim Egorushkin 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 sscanf:

 std::string mac = "00:00:12:24:36:4f";
unsigned u[6];
int c=sscanf(mac.c_str(),"%x:%x:%x:%x:%x:%x",u,u+1,u+2,u+3,u+4,u+5);
if (c!=6) raise_error("input format error");
uint64_t r=0;
for (int i=0;i<6;i++) r=(r<<8)+u[i];
// or:  for (int i=0;i<6;i++) r=(r<<8)+u[5-i];

原文由 Nordic Mainframe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题