How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values?
Thanks
How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values?
Thanks
Not sure if you mean cast or convert. If convert, then it depends in what form you want it. You might want Hex, base-64, octal, ...
If you want hex, consider STLSoft's format_bytes()
function, which can do all kinds of ordering and grouping.
If you want base-64, consider the b64 library.
HTH
[EDIT] In line with the edit on the OP, the full impl would be:
#include <stlsoft/conversion/byte_format_functions.hpp>
#include <stdio.h>
int main()
{
unsigned char mac[6];
char result[STLSOFT_NUM_ELEMENTS(mac) * 3];
stlsoft::format_bytes(mac, sizeof(mac), &result[0], STLSOFT_NUM_ELEMENTS(result), 1, ":");
puts(result);
return 0;
}
There's no need in this case to check the return value from format_bytes()
because you're passing in enough write buffer. In a real case you'd want to check
You probably want a sequence of six bytes to be formatted like so:
aa:bb:cc:dd:ee:ff
where aa
is the first byte formatted in hex.
Something like this should do:
char MAC[6]; //< I am assuming this has real content
std::ostringstream ss;
for (int i=0; i<6; ++i) {
if (i != 0) ss << ':';
ss.width(2); //< Use two chars for each byte
ss.fill('0'); //< Fill up with '0' if the number is only one hexadecimal digit
ss << std::hex << (int)(MAC[i]);
}
return ss.str();
If you dearly want to do this in a cast-like style (guessing from your title here), you can create a MAC class, implement the ostream-operator for it (like my given code) and use boost::lexical_cast
.