【linux c】c语言十进制数转换为十六进制输出_学习笔记_005

2016-08-29
#include <stdio.h>  #define uint unsigned int #define MAX_SIZE 1024    //数组长度   //十进制数字转换成十六进制字符串 char * num2hex(uint num) {     int i;     uint tmp;      uint mask = 0xf;            //掩码0x 0000 000f          static char hex[MAX_SIZE];  //存储十六进制字符串      hex[0] = '0';               //前两位固定不变,为0x     hex[1] = 'x';           //为其余元素赋值     for(i = 9; i >= 2; i--)     {         tmp = num & mask; 	    hex[i] = (tmp >= 10) ? ((tmp - 10)  + 'a') : (tmp + '0');  	    num  = num >> 4;     }      return hex; }  int main() {     uint num;          char * tmp;      printf("Please input a number:");     scanf("%d", &num);      tmp = num2hex(num);     printf("%d to hex is %s
", num, tmp);          return 0; }