将Mac字符串转换为字节数组

问题描述 投票:0回答:2

我有一个字符串(std::string),其中包含C ++中的MAC地址,例如:

10:10:0F:A0:01:00

我需要将其转换为字节数组(unsigned char*)。

字节必须从左到右写入。是否有人对此具有功能或有效的算法?

c++ bytearray mac-address
2个回答
0
投票

这会工作。您已将其标记为C ++,所以我谨慎地避免了使用sscanf C方法可能的较短解决方案。 using namespace std在这里仅用于缩短引用的代码。

#include <iostream>
#include <sstream>

main() {

  unsigned char octets[6];
  unsigned int value;
  char ignore;

  using namespace std;

  istringstream iss("10:10:0F:A0:01:00",istringstream::in);

  iss >> hex;

  for(int i=0;i<5;i++) {
    iss >> value >> ignore;
    octets[i]=value;
  }
  iss >> value;
  octets[5]=value;

  // validate

  for(int i=0;i<sizeof(octets)/sizeof(octets[0]);i++)
    cout << hex << static_cast<unsigned int>(octets[i]) << " ";

  cout << endl;
}

0
投票

很抱歉,但是为了帮助其他可能仍在寻找答案的人,有一种标准的C方式仍然可以在C ++中使用,而无需重新设计轮子。只需man ether_aton或单击here

© www.soinside.com 2019 - 2024. All rights reserved.