tags:

views:

413

answers:

3

How do I convert 6 bytes representing a MAC address into a string that displays the address as colon-separated hex values?

Thanks

+1  A: 
  1. Make sure it is null terminated
  2. You need to know what encoding the string is in. If it's ASCII, a simple std::string str((char*) your_buffer) will do. your_buffer should be an unsigned char. If it's not, we need more info.
Thanatos
If it's not null terminated, you can use std::string's assign() method, which optionally takes two additional arguments of starting position and number of characters, e.g. std::string str; str.assign(reinterpret_cast<char*>(buf), 0, 6);
Tyler McHenry
The input is a 6byte binary value that is supplied to me from the Net-SNMP library and all I need is the hex value it returns as it is a MAC address.
aHunter
I added this info to your question, since it was not at all clear that that's what you wanted to do.
Tyler McHenry
Thank you sorry I should have made it clearer.
aHunter
+3  A: 

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

DannyT
+4  A: 

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.

Magnus Hoff
Looks like you got there first :)
rlbond
Thank you this worked like a dream.
aHunter
I already had a cast.h and added this and it worked perfectly.
aHunter