/ / Napisz sformatowany adres mac do ciągu znaków - c ++

Napisz sformatowany adres MAC do stringstream - c ++

Mam następującą klasę (tylko częściowe, znacznie więcej pól w klasie)

class Network{
public:
string src_ip_;
string alternative_src_ip_;
array<unsigned char,6> mac_;
string toString(){
stringstream ss;
ss << src_ip_ << SEPERATOR << alternative_src_ip_ << SEPERATOR ;
return ss.str();
}
}

Chcę dodać sformatowany Mac (z :) do metody toString? Czy istnieje prosty sposób na przyjęcie mojej metody printMac (przez generelize lub napisanie nowej), która zrobi to w połączeniu z operatorem <<

void printMac(array<unsigned char, 6> mac) {
printf("%02x:%02x:%02x:%02x:%02x:%02xn",
(unsigned char) mac[0], (unsigned char) mac[1],
(unsigned char) mac[2], (unsigned char) mac[3],
(unsigned char) mac[4], (unsigned char) mac[5]);
}

Odpowiedzi:

2 dla odpowiedzi № 1

Możesz zastąpić użycie printf przez sprintf, a następnie użyć go do implementacji operatora << dla ostreams

void printMac(array<unsigned char, 6> mac, char (&out)[18]) {
sprintf(out, "%02x:%02x:%02x:%02x:%02x:%02x",
(unsigned char) mac[0], (unsigned char) mac[1],
(unsigned char) mac[2], (unsigned char) mac[3],
(unsigned char) mac[4], (unsigned char) mac[5]);
}

std::ostream &operator<<(std::ostream &os, std::array<unsigned char, 6> mac) {
char buf[18];
printMac(mac, buf);
return os << buf << "n";
}

3 dla odpowiedzi № 2

Użyj Manipulatory IO:

std::ostringstream s;
unsigned char arr[6] = { 0, 14, 10, 11, 89, 10 };

s << std::hex << std::setfill("0");

for (int i = 0; i < sizeof(arr); i++)
{
if (i > 0) s << ":";

// Need to:
//  - set width each time as it only
//    applies to the next output field.
//  - cast to an int as std::hex is for
//    integer I/O
s << std::setw(2) << static_cast<int>(arr[i]);
}

0 dla odpowiedzi № 3

Jeśli chcesz zachować kod podobny do printf, możesz spróbować Boost.Format.

ss << boost::format("%02x:%02x:%02x:%02x:%02x:%02xn") % mac[0] % mac[1] % mac[2] % mac[3] % mac[4] % mac[5];