MAC 地址的输出格式(C++、stringstream)
我找到了代码:
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]);
}
此函数打印 MAC 地址,如 00-53-45-00-00-00
我的问题:
如何在打印到 std 时使用这种格式::字符串流?
更新:
谢谢大家的建议!
我不知道为什么,但是一些没有 static_cast
的解决方案给了我奇怪的字符,例如 ☻-0→-0M-0Ы-0m-0╜
所以我选择 由 icecrime 提升版本 strong>:
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的解决方案 也很好用;)
谢谢!
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>
gave 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许有点偏离主题,但我个人会使用 Boost.Format< /a>:
Perhaps a little off topic, but I would personally use Boost.Format :
你可以这样做(不改变应用程序的现有设计(我猜你不能,否则你可能会这样做:)))
用法:
更新:十六进制格式:)
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 :)))
Usage:
Update: HEX format :)
首先,您应该将代码转换为使用 C++ 流和操纵器,例如
,然后您应该为左侧的流和右侧的类重载
<<
运算符。First you should convert your code to use C++ streams and manipulators, e.g.
Then you should overload the
<<
operator for a stream on the left side and your class on the right.