Today, when dealing with a MAC address, a problem that has not been noticed before is documented.
When the string format output is needed, the Format function is automatically thought of, and the MAC address needs to be output in two-bit width 16, so I write%x directly, but I get an error output format in the actual output: • " Fffffff0 ", it should be f0 ah.
First of all to determine their own program is not wrong, and then simple analysis, as long as the 0xf* this will become the case above, it is obvious that should be a carry or sign bit problem.
Google, find a blog introduction printf, excerpts inside a paragraph:
The reason for this is that%x is unsigned int or int type output, so printf ("%x", a) automatically promotes a type (char will elevate to int;unsigned char to unsigned int) at execution time, note To Char is signed (signed), if A is a negative number, it will be preceded by a 1 in advance, that is, 0xf1 => 0xfffffff1 in the inverse example, and unsigned char will only make up 0 when ascending. ”
So the solution is clear:
Str1. Format ("%02x", (unsigned char) mac[3]);
Str2. Format ("%02hhx", Mac[3]);
Str3. Format ("%02x", (Mac[3] & 0xff));
The above represents three methods:
The first line is cast.
The second line is the exact print format
The third line is forced into 1byte