Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MAC address std::string into uint64_t

Tags:

c++

unix

I have a hexadecimal MAC address held in a std::string. What would be the best way to turn that MAC address into an integer-type held in a uint64_t?

I'm aware of stringstream, sprintf, atoi, etc. I've actually written little conversion functions with the first 2 of those, but they seem more sloppy than I would like.

So, can someone show me a good, clean way to convert

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

into a uint64_t?

PS: I don't have boost/TR1 facilities available and can't install them where the code will actually be used (which is also why I haven't copy pasted one of my attempts, sorry about that!). So please keep solutions to straight-up C/C++ calls. If you have an interesting solution with a UNIX system call I'd be interested too!

like image 711
John Humphreys Avatar asked Sep 06 '11 21:09

John Humphreys


1 Answers

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])
        );
}
like image 174
Maxim Egorushkin Avatar answered Sep 22 '22 20:09

Maxim Egorushkin