十进制的数转换成十六进制的数 (转)

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
/*
 * 方    法: decimal2Hex
 * 功    能:十进制的数转换成十六进制的数 
 * 参    数:int  num : 十进制的数 
 * 返回值:char * : 十六进制的字符 
 */
 char * decimal2Hex(int num){

    int a[100]; 
    int i=0; 
    int m=0;
    int yushu; 
    char hex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    while(num>0) 
    { 
        yushu=num%16; 
        a[i++]=yushu; 
        num=num/16; 
    } 
    
    char *buffer = (char*) malloc(4 * sizeof(char));
    memset(buffer, 0x00, sizeof(buffer));
    
    for(i=i-1;i>=0;i--)//倒序输出 
    { 
        m=a[i];
        buffer[i] = hex[m];
    
    }
    sprintf(buffer, "%c%c%c%c",'0','x',buffer[1],buffer[0]);
    return buffer;
}

int main(){
     // char *strResult = decimal2Hex(40);  28(HEX)
     char *strResult = decimal2Hex(255);    //FF(HEX)
     printf("测试结果:%s",strResult);
}

原文地址:https://www.cnblogs.com/YangBinChina/p/4239169.html