C ++将mac id字符串转换为uint8_t数组 [英] C++ converting a mac id string into an array of uint8_t
问题描述
我想从命令行读取一个mac id,并将其转换为 uint8_t
值的数组,以在结构中使用它。我不能让它工作。我有一个向量的字符串的mac id拆分约:
,我想使用 stringstream
运气。
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 string for the mac id split about :
and I want to use stringstream
to convert them with no luck. What I am missing?
int parseHex(const string &num){
stringstream ss(num);
ss << std::hex;
int n;
ss >> n;
return n;
}
uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
v = StringSplit( mac , ":" );
for( int j = 0 ; j < v.size() ; j++ ){
tgt_mac[j] = parseHex(v.at(j));
}
推荐答案
这种方式,但 sscanf()
可能是最简洁的方法来解析出一个MAC地址。它处理零/非零填充,宽度检查,大小写折叠和所有其他的东西,没有人喜欢处理。无论如何,这里是我不是那么C ++版本:
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<uint8_t>& 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]);
}
这篇关于C ++将mac id字符串转换为uint8_t数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!