Note in C + +, 0 extension and sign bit extension

Source: Internet
Author: User

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

First, describe the definitions of the two extensions

Turn http://blog.csdn.net/jaylong35/article/details/6160736

Symbol extension: When storing a signed number with more memory, since the sign bit is in the first bit of the number, after the expansion, the sign bit still needs to be in the first place, so when you extend a negative, you need to fully assign the extension to 1. For positive numbers, the symbol extension is the same as the 0 extension because the sign bit is 0.
For example, a 8-bit binary representation-1, then 10000001
If the book is represented in 16-bit binary, then the 11111111 10000001 High is all 1, this is called the symbol extension, which is used primarily for its operands.

0 extension is full complement 0. No matter what the sign bit is, the high 8 bits all complement 0.


The above definition can be seen in C + +, if you convert a char to a shaping, there will be this problem

If you want a positive number, then if the ASCII value of one character is less than 0, and the direct type is cast with (int) C, the result is a negative number from the symbol extension. To get a positive number, be sure to use (int) (unsigned char) c, because unsigned char removes the sign bit of C, so after such a type conversion, the conversion with (int) is a positive number.

Examples are as follows:

[C-sharp]View PlainCopy
  1. #include <stdio.h>
  2. int main ()
  3. {
  4. int i = 129;
  5. Char cha= (char) i;
  6. int c = (int) (unsigned char) ChA;
  7. int b = (int) ChA;
  8. printf ("sign extension:%d/n", b);
  9. printf ("zero extension:%d/n", c);
  10. System ("pause");
  11. return 1;
  12. }

Operation Result:

Sign Extension:-127
Zero extension:129
Please press any key to continue ...

Note in C + +, 0 extension and sign bit extension

Related Article

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.