一、同类型的数据和同类型指针之间的转换
23 #include <sys/stat.h>
22 #include <stdio.h>
21 #include <stdlib.h>
20 #include <string.h>
19 #include <stdarg.h>
7 int main(int argc, char *argv[])
6 {
5 | unsigned int ret = 11;
4 | unsigned int *ret1 = &ret; //指针ret1 指向ret所在的地址
3
2 | printf("%x\n", *ret1);
1 | return 0;
34 }
原因:
指针ret1
指向ret
所在的地址 ,如果将unsigned int 类型转换成指针的表示方法,见如下方式:
26 int main(int argc, char *argv[])
27 {
28 | unsigned int ret = 11;
29
30 | printf("ret:%d\n", ret);
31 | printf("*(unsigned int *)ret:%d\n", *(unsigned int *)&ret);
32
33 | return 0;
34 }
结果:
ret:11
*(unsigned int *)ret:11
从结果上可以看到,两个结果相同,这也就是说unsigned int ret
和*(unsigned int *)&ret
是等价的。
二、不同类型的数据和指针之间的转换
以下是int
和char
数组之间的类型转换
8 #include <sys/stat.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdarg.h>
13
15 int main(int argc, char *argv[])
16 {
17 | unsigned int ret = 0;
18 | unsigned char buffer[4] = {0x01, 0x02, 0x03, 0x04};
19
20 | ret = *(unsigned int *)buffer;
21 | printf("%x\n", ret);
22
23 | return 0;
24 }
通过将数据类型转换成指针的方式不用考虑不同数据类型之间的大小即可实现不同类型之间的转换。除了上述方式也可以通过memcpy
和方式进行转换。memcpy
实现方式如下:
备注:
23 int main(int argc, char *argv[])
24 {
25 | unsigned int ret = 0;
26 | unsigned char buffer[4] = {0x01, 0x02, 0x03, 0x04};
27
28 | memcpy(&ret, buffer, sizeof(unsigned int));
29 | printf("%x\n", ret);
30
31 | return 0;
32 }