I want to read a mac id from command line and convert it to an array of uint8_t
values to use it in a struct. I can not get it to work. I have a vector of string for the mac id split about :
and I want to use stringstream
to convert them with no luck. What I am missing?
int parseHex(const string &num){
stringstream ss(num);
ss << std::hex;
int n;
ss >> n;
return n;
}
uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
v = StringSplit( mac , ":" );
for( int j = 0 ; j < v.size() ; j++ ){
tgt_mac[j] = parseHex(v.at(j));
}
I hate to answer this in this fashion, but
sscanf()
is probably the most succinct way to parse out a MAC address. It handles zero/non-zero padding, width checking, case folding, and all of that other stuff that no one likes to deal with. Anyway, here's my not so C++ version:I think you are using the std::hex in the wrong place:
First I want to point out that I think @Steven's answer is a very good one - indeed I noticed the same: the values are correct, but the output looks awkward. This is due to
ostream& operator<<( ostream&, unsigned char )
being used, since theuint8_t
type you used is a typedef forunsigned char
(as I found in the linux man pages). Note that on VC++, the typedef isn't there, and you have to useunsigned __int8
instead (which will also route you to thechar
specialization).Next, you can test your code like this (output-independent):
In addition to Steven's answer, I just want to point out the existence of the
transform
algorithm, which could still simplify your code.Writes in one line:
(And I know that hasn't to do with the question...)
(See codepad.org for what it then looks like)
Your problem may be in the output of the parsed data. The "<<" operator makes decisions on how to display data based on the data type passed it, and uint8_t may be getting interpretted as a char. Make sure you cast the array values to ints when printing, or investigate in a debugger.
The sample program:
Gives the following output ( cygwin g++ )