0

I have a string (std::string) which contains a MAC address in C++, e.g.:

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

I need to convert it to an array of bytes (unsigned char*).

The bytes have to be written from left to right. Does anybody have a function or efficient algorithm for this?

Pang
  • 9,564
  • 146
  • 81
  • 122
Crimson
  • 11
  • 1
  • 2
  • 1
    haha @herohuyongtao. i don't think that's what he means... – thang Sep 26 '14 at 06:28
  • You can use [`std::istringstream`](http://en.cppreference.com/w/cpp/io/basic_istringstream) along with the `hex` I/O manipulator, and use `:` as delimiter, to read in the equivalent numbers into a 6 byte array. – πάντα ῥεῖ Sep 26 '14 at 06:28
  • ok, sorry, I forgot to mention that the ":"-chars should be removed:-) – Crimson Sep 26 '14 at 06:31
  • Do you have a code-example for the std::isstringstream with hex I/O manipulator and : as delimiter, I think it's really waht I need but can't find an example. – Crimson Sep 26 '14 at 06:33
  • I actually have an [example here](http://stackoverflow.com/questions/24504582/test-whether-stringstream-operator-has-parsed-a-bad-type?noredirect=1#comment37965807_24504582) that shows how to skip bad input, should also work for your case. Though there are other possible solutions (e.g. `std::getline()` allows to specify an alternate delimiter). – πάντα ῥεῖ Sep 26 '14 at 06:47
  • Take care when reading in the numbers. Use an `int` in 1st place to read in, and cast the number to the target `uint8_t` afterwards. – πάντα ῥεῖ Sep 26 '14 at 06:50

2 Answers2

3

Sorry for necroposting, but just to help others who may still be searching for the answer, there is a standard C way that still can be used in C++ without any reinvention of the wheel. Just man ether_aton or click here.

Alexander Amelkin
  • 759
  • 1
  • 9
  • 15
0

This'll work. You've tagged this as C++ so I've scrupulously avoided the shorter solution that's possible using the sscanf C method. using namespace std is used here only to shorten the quoted code.

#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;
}
Andy Brown
  • 11,766
  • 2
  • 42
  • 61