I am currently working with parsing some MAC addresses. I am given an output that does not include leading zeros (like so).
char* host = "0:25:25:0:25:25";
and I would like to format it like so
char* host = "00:25:25:00:25:25";
What would be the easiest way to go about this?
For those wondering, I am using the libpcap library.
I may be missing something in the question. Assuming you know it is a valid MAC, and the input string is thus parsable, have you considered something as simple as:
Output
Obviously for the ultra-paranoid you would want to make sure
a-f
are all < 255, which is probably preferable. The fundamental reasons I prefer this where performance isn't a critical issue are the many things you may not be considering in your question. It handles all of"n:"
, wheren
is any hex digit; not just zero. Examples:"5:"
,"0:"
":n:"
, again under the same conditions as (1) above. Examples:":A:"
,":0:"
":n"
. once more, under the same conditions as (1) above. Examples:":b"
,":0"
Roughly like this: Allocate an output string to hold the reformatted MAC address. Iterate over the input string and use
strtok
with:
delimiter. In each iteration convert the beginning of the string (2 bytes) into a numerical value (e.g., withatoi
). If the result < 16 (i.e., < 0x10), set"0"
into the output string at current position and the result in hex at the following position; otherwise copy the 2 bytes of input string. Append:
to the output string. Continue till end of the input.