From the Nginx source code, we will talk about the most efficient code for converting uppercase and lowercase characters and the science of ASCII code tables.

Source: Internet
Author: User

From the Nginx source code, we will talk about the most efficient code for converting uppercase and lowercase characters and the science of ASCII code tables.

The nginx source code is as follows:

Nginx-1.6.1/src/core/ngx_string.h 47-48 rows

#define ngx_tolower(c)      (u_char) ((c >= 'A' && c <= 'Z') ? (c | 0x20) : c)#define ngx_toupper(c)      (u_char) ((c >= 'a' && c <= 'z') ? (c & ~0x20) : c)


Obviously, some people use bitwise operations, but why?

First look at the AscII code table:


We only focus on the uppercase letters A-Z and lowercase letters a-z.

Note that A is 65, Z is 90, and a is 97. Unexpectedly, I don't know how many people have thought about it. Why isn't Z and a continuous? That is to say, why do we need to add some other special characters between 91-96?


In fact, this is not "This is what it is ". However, this arrangement is very scientific. For more information, see Wang Shuang's assembly language:

The reason for doing so is to make it easy to convert the case to each other, that is, bitwise operations can be used. If a is not 97 but 91, bitwise operations are not good.


The binary value of decimal 65 is 01000001.

The binary value of 0x20 in hexadecimal format is 00100000.


The 97 binary value in decimal format is 01100001. Therefore, to convert the value in uppercase to lowercase, The 01000001 and 00100000 must be "or.


Convert lowercase to uppercase to 01100001

~ 0x20 indicates bitwise inversion, that is, 0xdf. The binary value is 11011111,01100001 & 11011111 = 01000001.


In fact, the formula can be obtained:

If A | B = C => A = C &~ B

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.