MFC C + + Format 16 in the output of the need to note a little __c++

Source: Internet
Author: User
Tags print format string format

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.