strncpy()
1.常用用法
-
strncpy(buff, src, sizeof(buff));
-
buff[sizeof[buff]-1] = '\0';
snprintf()
1.常用用法
-
snprintf(buff, sizeof(buff), "%s", src);
另外,还有如:
-
snprintf(buff, sizeof(buff), src);
或
也是可以的。
2.实战问题
关于使用sprintf时符号扩展的问题:
首先,符号扩展:即当短数据赋值给长数据时,将短数据的符号位填充到长数据的高字节位,以保证扩展后的数值大小不变。零扩展:即当短数据赋值给长数据时,用零来填充长数据类型的高字节位。
其次,我们直接看遇到的问题及分析过程:
-
#include <stdio.h>
-
-
int main()
-
{
-
char mac[6] = {0x01,0x8b,0x03,0x04,0x05,0x06};
-
char str[64] = {0};
-
-
sprintf(str, "%02x", mac[1]);
-
-
printf("%s\n", str);
-
-
return 0;
-
}
输出结果是
0xffffff8b
把问题简单化后
-
#include <stdio.h>
-
-
int main()
-
{
-
char a = 0x8b;
-
-
printf("%#02x\n", a);
-
-
return 0;
-
}
输出结果是
0xffffff8b
这里,我们先明确下width的功能
再试着这样做
-
#include <stdio.h>
-
-
int main()
-
{
-
char a = 0x8b;
-
int b = a;
-
unsigned int c = a;
-
-
printf("%#02x %#02x\n", b, c);
-
-
return 0;
-
}
输出结果是
0xffffff8b 0xffffff8b
这里,我们用gcc -S sprintf3.c后,vim sprintf3.s来查看汇编代码
-
.file "sprintf3.c"
-
.section .rodata
-
.LC0:
-
.string "%#02x %#02x\n"
-
.text
-
.globl main
-
.type main, @function
-
main:
-
pushl %ebp
-
movl %esp, %ebp
-
andl $-16, %esp
-
subl $32, %esp
-
movb $-117, 31(%esp)
-
movsbl 31(%esp),%eax
-
movl %eax, 24(%esp)
-
movsbl 31(%esp),%eax
-
movl %eax, 20(%esp)
-
movl $.LC0, %eax
-
movl 20(%esp), %edx
-
movl %edx, 8(%esp)
-
movl 24(%esp), %edx
-
movl %edx, 4(%esp)
-
movl %eax, (%esp)
-
call printf
-
movl $0, %eax
-
leave
-
ret
-
.size main, .-main
-
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
-
.section .note.GNU-stack,"",@progbits
显然,与这里的movsbl有关系,我们来看看什么是movsbl?(图片来自:)
那么,sprintf3.c应该这样写,才是我本来的意图
-
#include <stdio.h>
-
-
int main()
-
{
-
char a = 0x8b;
-
int b = (unsigned char)a;
-
unsigned int c = (unsigned char)a;
-
-
printf("%#02x %#02x\n", b, c);
-
-
return 0;
-
}
输出结果才是我想要的
0x8b 0x8b
而开头的mac程序,也应该是这样写
-
#include <stdio.h>
-
-
int main()
-
{
-
char mac[6] = {0x01,0x8b,0x03,0x04,0x05,0x06};
-
char str[64] = {0};
-
-
sprintf(str, "%02x", (unsigned char)mac[1]);
-
-
printf("%s\n", str);
-
-
return 0;
-
}
输出结果才是我想要的
0x8b
其实,该问题早在sprintf的百度百科中早已说明了
阅读(41605) | 评论(0) | 转发(0) |