C语言整型转字符串如0x68656c6c转为“hell”,不是123转“123”的问题
C语言整型转字符串如0x68656c6c转为“hell”,不是123转“123”的问题
int i = 0x68656c6c;
查ascii码是这样的:hell
但是我通过i怎么计算能达到:
char type[4] = "hell".
我效果。
实际问题是这样的,内存中有 0x68656c6c,我现在能把它读出来。(这里不说大小端,这个我会解决)。我想把它存到char type[4]中,像这样char type[4] = "hell".
[解决办法]
1 #include <stdio.h>
2 #include <string.h>
3 #include <arpa/inet.h>
4 int main(int argc, char *argv[])
5 {
6 int i = 0x68656c6c, j;
7 char tmp[5];
8 j = ntohl(i);
9 memcpy(tmp, (char *)&j, 4 * sizeof(char));
10 tmp[4] = 0;
11 printf("%s\n", tmp);
12 return 0;
13 }