背景:
unsigned char port[5];
以02x的格式打印出来是 00 00 02 00 00
1.如何转成16进制形式的字符串,使得char *strport16 = "0000020000";
2.如何转成10进制形式的字符串,使得char *strport10 = "131072";
C code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned char port[5] = {0x00, 0x00, 0x02, 0x00, 0x00};
char buf[20] = {0};
// format port[] to hex result
sprintf(buf, "%02x%02x%02x%02x%02x", port[0], port[1], port[2], port[3], port[4]);
printf("十六进制:\t%s\n", buf);
// format port[] to decimal result
__int64 a = 0;
memcpy(&a, port, sizeof(port)); // ensure the length of port[] is less than or equal to 8
sprintf(buf, "%I64d\n", a); // format an integer of 64bit length
printf("十进制:\t\t%s\n", buf);
__int64 bb = 0x1122334455667788;
unsigned char *p = (unsigned char*)&bb;
printf("bb = 0x%I64x\n", bb);
for(int i = 0; i < sizeof(bb); i++)
{
printf("%02x ", p[i]); // high part bytes store at high memory address
}
printf("\n");
return 0;
}
运行结果:
十六进制: 0000020000
十进制: 131072
bb = 0x1122334455667788
88 77 66 55 44 33 22 11
Press any key to continue
结论:整数的高位字节保存在高地址处,而且局部变量是保存在栈区的,在内存中的情况如图: