0x%02x 16-Input output of the character type

Source: Internet
Author: User

Problem: A character type in 16 output, the output format is 0xAB, 0x is required after 2 bits, not enough 2 bit 0, such as "0x0b".

Common error practices are:

  1. #include <stdio.h>
  2. int Main ()
  3. {
  4. char a = 0x41; //A = ' a '
  5. printf ( "The hex value of a is 0x%02x\n", a);
  6. return 0;
  7. }

If a = 0xf1, the above output will be 0xfffffff1 instead of 0XF1.

The reason forthis is that%x is unsigned int or int output , so printf ("%x", a) will automatically raise the a type when executed (char will be promoted to int;

Unsigned char will be promoted to unsigned int), note that Char is signed (signed),

If A is negative at this point, it will be 1 in front of the promotion, i.e. 0xf1 = 0xfffffff1 in the inverse example, and unsigned char It only makes up 0 when it's lifted.

Workaround 1. Forcing type conversions
  1. #include <stdio.h>
  2. int Main ()
  3. {
  4. char a = 0xf1;
  5. printf ( "The hex value of a is 0x%02x\n", (unsigned char) a);
  6. return 0;
  7. }

Method 2. Precise printing format
  1. #include <stdio.h>
  2. int Main ()
  3. {
  4. char a = 0xf1;
  5. printf ( "The hex value of a is 0x%02hhx\n", a);
  6. return 0;
  7. }

HH will convert int to char;unsigned int into unsigned char. Specifically you can see the details in Man 3 printf.

Shell Code 
  1. HH A Following integer conversion corresponds to A signed char or unsigned char argument,
  2. or a following n conversion corresponds to a pointer to a signed char argument.
Method 3. The number of forced bits is 1 byte
  1. #include <stdio.h>
  2. int Main ()
  3. {
  4. char a = 0xf1;
  5. printf ( "The hex value of a is 0x%02x\n", (A&0xff));
  6. return 0;
  7. }

The implicit procedure above is to raise char a to int, and then to 0xFF.

0x%02x 16-Input output of the character type

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.