output format for mac address (C++, stringstream)
I found code:
static void PrintMACaddress(unsigned char MACData[])
{
printf("MAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n",
MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
}
this function prints MAC address like 00-53-45-00-00-00
My quesion:
How to make such format while printing into std::stringstream
?
Update:
Thank you all for your advices!
I do not know why, but some of solutions without static_cast<unsigned int>
gav开发者_StackOverflow中文版e me strange characters like ☻-0→-0M-0Ы-0m-0╜
So I choose boost version by icecrime:
void PrintMACaddressWithBoostFormat(unsigned char MACData[])
{
boost::format fmt("%02X-%02X-%02X-%02X-%02X-%02X");
for (int i = 0; i != 6; ++i)
{
fmt % static_cast<unsigned int>(MACData[i]);
}
std::stringstream valStream(fmt.str().c_str());
//testing
std::cout << "Boost version: " << valStream.str().c_str() << std::endl;
}
Palmik's solution works great, too;)
Thank you!
Perhaps a little off topic, but I would personally use Boost.Format :
boost::format fmt("%02X-%02X-%02X-%02X-%02X-%02X");
for (int i = 0; i != 6; ++i)
fmt % static_cast<unsigned int>(MACData[i]);
std::cout << fmt << std::endl;
You could do it like this (without changing the existing design of the app (I guess you can not, otherwise you would probably do it :)))
void printMacToStream(std::ostream& os, unsigned char MACData[])
{
// Possibly add length assertion
char oldFill = os.fill('0');
os << std::setw(2) << std::hex << static_cast<unsigned int>(MACData[0]);
for (uint i = 1; i < 6; ++i) {
os << '-' << std::setw(2) << std::hex << static_cast<unsigned int>(MACData[i]);
}
os.fill(oldFill);
// Possibly add:
// os << std::endl;
}
Usage:
std::stringstream ss;
printMacToStream(ss, arrayWIthMACData);
Update: HEX format :)
char prev = stream.fill('0'); // save current fill character
for(int i=0; i<5; i++)
stream << setw(2) << MACData[i] << '-';
stream << setw(2) << MACData[5];
stream.fill(prev); // restore fill character
First you should convert your code to use C++ streams and manipulators, e.g.
std::cout << std::hex << std::setw(2) << std::setfill('0') << MACData[0] ...
Then you should overload the <<
operator for a stream on the left side and your class on the right.
精彩评论