【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; }


  
  

http://m.juhua625748.cn|http://wap.juhua625748.cn|http://www.juhua625748.cn||http://juhua625748.cn