关于编译器无法识别字符串中十六进制转议字符(\xff)和普通字符的问题

Really_want Really_want 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
无意间发现一个有趣的情况,也不知这算不算一个问题。在网上还没找到相关的令我比较信服的解释。如下图所示:

预期,3行输出的结果应该是相同的,都将解释为两个字节的数据: 0x5,0x31
但是,实际运行结果,并不如此。如果将这两个字节的数据用普通字符('1')和转义字符(\x05)混合存到字符串(p2)中,将不能得到预期结果。十六进制转义字符,我采用的是\xff格式;我也用过 \xddd,\xdddd 格式,结果均相同。
参考汇编后的代码,问题出在把"\051"解释成了"Q\0" !
参考:
https://msdn.microsoft.com/zh-cn/library/edsza5ck.aspx
http://blog.csdn.net/shangboerds/article/details/7543832
http://www.cnblogs.com/graphics/archive/2011/07/08/2100909.html

//helloworld.cpp
#include <cstdio>

int main(int argc,char*argv[])
{
char ch[2] = {'\x05', '1'};
const char* p = "\x05\x31";
const char* p2 = "\x051";
printf("ch:%x,%x\n",ch[0],ch[1]);
printf("p :%x,%x\n",p[0],p[1]);
printf("p2:%x,%x\n",p2[0],p2[1]);
return 0;
}

//makefile
exes = a.exe a.s

target: $(exes)

a.exe: helloworld.cpp dump.h
g++ -Wall -O0 -o a.exe helloworld.cpp

a.s: helloworld.cpp
g++ -S -o a.s helloworld.cpp

clean:
cmd //C del $(exes)

//a.s
.file "helloworld.cpp"
.def ___main; .scl 2; .type 32; .endef
.section .rdata,"dr"
LC0:
.ascii "\5"
.ascii "1\0"
LC1:
.ascii "Q\0"
LC2:
.ascii "ch:%x,%x\12\0"
LC3:
.ascii "p :%x,%x\12\0"
LC4:
.ascii "p2:%x,%x\12\0"
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB12:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
andl $-16, %esp
subl $32, %esp
call ___main
movb $5, 22(%esp)
movb $49, 23(%esp)
movl $LC0, 28(%esp)
movl $LC1, 24(%esp)
movzbl 23(%esp), %eax
movsbl %al, %edx
movzbl 22(%esp), %eax
movsbl %al, %eax
movl %edx, 8(%esp)
movl %eax, 4(%esp)
movl $LC2, (%esp)
call _printf
movl 28(%esp), %eax
addl $1, %eax
movzbl (%eax), %eax
movsbl %al, %edx
movl 28(%esp), %eax
movzbl (%eax), %eax
movsbl %al, %eax
movl %edx, 8(%esp)
movl %eax, 4(%esp)
movl $LC3, (%esp)
call _printf
movl 24(%esp), %eax
addl $1, %eax
movzbl (%eax), %eax
movsbl %al, %edx
movl 24(%esp), %eax
movzbl (%eax), %eax
movsbl %al, %eax
movl %edx, 8(%esp)
movl %eax, 4(%esp)
movl $LC4, (%esp)
call _printf
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
LFE12:
.ident "GCC: (GNU) 5.3.0"
.def _printf; .scl 2; .type 32; .endef

...全文

相关推荐

评论 20
收藏 已收藏
分享
返回顶部
Really_want
C语言 70,038 成员 243,237 内容