C++ converting a mac id string into an array of uint8_t

前端 未结 4 1023
小蘑菇
小蘑菇 2021-01-15 17:42

I want to read a mac id from command line and convert it to an array of uint8_t values to use it in a struct. I can not get it to work. I have a vector of stri

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 18:26

    I hate to answer this in this fashion, but sscanf() is probably the most succinct way to parse out a MAC address. It handles zero/non-zero padding, width checking, case folding, and all of that other stuff that no one likes to deal with. Anyway, here's my not so C++ version:

    void
    parse_mac(std::vector& out, std::string const& in) {
        unsigned int bytes[6];
        if (std::sscanf(in.c_str(),
                        "%02x:%02x:%02x:%02x:%02x:%02x",
                        &bytes[0], &bytes[1], &bytes[2],
                        &bytes[3], &bytes[4], &bytes[5]) != 6)
        {
            throw std::runtime_error(in+std::string(" is an invalid MAC address"));
        }
        out.assign(&bytes[0], &bytes[6]);
    }
    

提交回复
热议问题