将一个BYTE数组转换成16进制字符串和10进制字符串格式

来源:互联网 发布:免费会计记账软件 编辑:程序博客网 时间:2024/05/23 20:54

背景:

 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 resultsprintf(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 8sprintf(buf, "%I64d\n", a);// format an integer of 64bit lengthprintf("十进制:\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十进制:         131072bb = 0x112233445566778888 77 66 55 44 33 22 11Press any key to continue


结论:整数的高位字节保存在高地址处,而且局部变量是保存在栈区的,在内存中的情况如图:

原创粉丝点击