目录
一、释义
\ddd | ddd表示1~3个八进制数字,即将 \ 后的八进制数 ddd 转化为ASCII码值; |
\xdd | dd表示2个十六进制数字,即将 \x 后的十六进制数 dd 转化为ASCII码值; |
二、示例
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "\x66\\123\1234";
printf("字符总数:%d\n", strlen(s));
printf("字符串:%s\n", s);
return 0;
}
//输出结果:
字符总数:7
字符串:f\123S4
以上代码中:
' \x66 '、' \\ '、' 1 '、' 2 '、' 3 '、' \123 '、' 4 ' 各为一个字符,共7个字符;
三、等价的编译方式
同一个字符,可以使用 各种不同进制 或 ASCII码表 的形式输出;
#include <stdio.h>
#include <string.h>
int main()
{
char c1 = 'A';
char c2 = 65;
char c3 = '\x41';
char c4 = '\101';
printf("c1=%c\n", c1);
printf("c2=%c\n", c2);
printf("c3=%c\n", c3);
printf("c4=%c\n", c4);
return 0;
}
//输出结果:
c1=A
c2=A
c3=A
c4=A
字符 ' A ' 的ASCLL码值为 65 ;
十进制数 65 转换为十六进制数字是 41 ;
十进制数 65 转换为八进制数字是 101 ;
四、\ 后的数字超过进制范围
如果编译中出现超出进制范围的数字,编译器会将超出的数字单独解释为一个字符;
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "\x1h\018";
printf("字符总数:%d\n", strlen(s));
printf("字符串:%s\n", s);
return 0;
}
//输出结果为:
字符总数:4
字符串:h8
' \x1 '、' h '、' \01 '、' 8 ' 各被解释为一个字符,共4个字符;
十六进制的数字范围为 0~9,a~f ;
八进制的数字范围为 0~7 ;
' h ' 和 ' 8 ' 超过了各自进制的数字范围;
五、\ 后的数字不足
示例:需要输出由字符 ' \02 '、 ' 7 ' ,2个字符组成的字符串;
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "\027";
printf("字符总数:%d\n", strlen(s));
printf("字符串:%s\n", s);
return 0;
}
//输出结果为:
字符总数:1
字符串:
得出的结果只有一个字符,与需求不符;
' \ ' 后数字少于三位数,编译器会自动将后续字符解释为这个八进制数字的一部分;
因此,在编译八进制数字字符时,如果数字个数不足,应该在数字前补0,直到满足 \ddd 的转义格式;
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "\0027";
printf("字符总数:%d\n", strlen(s));
printf("字符串:%s\n", s);
return 0;
}
//输出结果:
字符总数:2
字符串:7
六、与释义不符的十六进制转义字符
十六进制转义字符 \xdd ,被解释为:dd表示2个十六进制数字,即将 \x 后的十六进制数 dd 转化为ASCII码值;
但事实真的如此吗?
#include <stdio.h>
#include <string.h>
int main()
{
char* s[] = { "\x66","\x066","\x0066","\x000000000066"};
for (int i = 0; i < 4; i++)
{
printf("字符总数:%d , 字符串:%s\n", strlen(s), s[i]);
}
return 0;
}
//输出结果:
字符总数:6 , 字符串:f
字符总数:6 , 字符串:f
字符总数:6 , 字符串:f
字符总数:6 , 字符串:f
无论在 ' \x ' 后增加多少数字,只要不超过十六进制数的数字范围和表示范围,都会被解释为十六进制数的一部分;
这真的很不合理!举个例子,如果真的需要连续打印字符 ' \x06 ' 和 ' 6 ' ,就无法通过以上方式直接打印,只能采取断开字符串的方式了;
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "\x066";
printf("字符串:%s\n", s1);
char s2[] = "\x06""6";
printf("字符串:%s\n", s2);
return 0;
}
字符串:f
字符串:6
( 哈哈哈~~ 文章结束!)
( 看到这里,如果有为各位帅哥美女提供一点点灵感,请点一个小小的赞哦,比心💖💖💖 )