Understanding of the char type and understanding of the complement code. Understanding of the char type

Source: Internet
Author: User

Understanding of the char type and understanding of the complement code. Understanding of the char type

I encountered such a small program today and thought it was easy to ignore some of the problems!

The program code is as follows:

The result of the program is:

I think a lot of white people like me may start to wonder why the final result is 255! First, we need to know that strlen () is a function used to calculate the string length, but why is the final String Length 255? Isn't there 1000 elements in the defined array a, and the for loop is also executed 999 times?

For char, we need to know that its implicit end mark is \ 0. When the compiler recognizes a char type variable and reads \ 0, it indicates the end. For this program, we also need to pay attention to the value range of char:-128 ~ 127

So when I = 128, a [128] =-1-128 =-129, the problem occurs here. The minimum value of the element in a can only be-128. What should I do? Here we need to know that in a computer, data is stored in the form of a complement,-128 encoding in the computer is 1000 0000, and-1 Completion code is 1111 1111, therefore, the complement code of-129 is 1 0111 1111, but the binary bit in char is only eight bits, so the highest bit is discarded. The rest is used as the complement code, that is, 0111 1111 (0x7f) through the loop, subtract one 0x7d, 0x7c, 0x7b, 0x7a, 0x79,0x78,0x77,0 x, 0x71, 0x70 ...... 0x00, so when the encoding is 0x00, a [255] = 0; so when a [255] = 0, as the string end sign, in a [0] ~ The elements of a [254] are not 0, so the final execution result is that the length of string a is 255.

 

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.