转换字符大小写(Nginx、PHP、Redis源码)

剖析源码中如何做

Nginx源码中转换字符大小写

1
2
3
4
5
6
7
8
9
10
/*
* 字符范围 十进制表示 二进制表示
* A-Z 65-90 0100 0001 - 0101 1010
* a-z 97-122 0110 0001 - 0111 1010
* 由于0x20(2^6)该位在大写二进制中是0,小写二进制中是1
* 则利用 | 将大写改为小写
* 则利用 & ~0x20 将小写改为大写
*/
#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)

Redis源码中转换字符大小写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Apply tolower() to every character of the sds string 's'. */
void sdstolower(sds s) {
int len = sdslen(s), j;

//调用C的库函数
for (j = 0; j < len; j++) s[j] = tolower(s[j]);
}

/* Apply toupper() to every character of the sds string 's'. */
void sdstoupper(sds s) {
int len = sdslen(s), j;

for (j = 0; j < len; j++) s[j] = toupper(s[j]);
}

PHP源码中转换字符大小写 (strtolower,strtoupper函数具体实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
PHPAPI char *php_strtolower(char *s, size_t len)
{
unsigned char *c, *e;

c = (unsigned char *)s;
e = c+len;

while (c < e) {
*c = tolower(*c);
c++;
}
return s;
}

PHPAPI char *php_strtoupper(char *s, size_t len)
{
unsigned char *c, *e;

c = (unsigned char *)s;
e = (unsigned char *)c+len;

while (c < e) {
*c = toupper(*c);
c++;
}
return s;
}
xpisme wechat
微信号