十进制十六进制互转、数字转字符、日期转总天数


#include<stdio.h>
/*
将十六进制转换成十进制输出
*/
void hex2dec(char *hex)
{
int result = 0;
int temp;
while(*hex != '\0')
{
if(*hex>='0' && *hex<='9')
{
temp = *hex - '0';
}
else if(*hex>='A' && *hex<='F')
{
temp = *hex - 'A' + 10;
}
else if(*hex>='a' && *hex<='f')
{
temp = *hex - 'a' + 10;
}
result += temp;
if(*(hex+1) != '\0')
{
result = result*16;
}
hex++;
}
printf("%d", result);
}

/*
将十进制转换成十六进制输出
*/
void dec2hex(int dec)
{
int hex;
if(dec<16)
{
hex = dec;
}
else
{
//余数
int x = dec%16;
//对商进行递归
dec2hex(dec/16);
//递归最外层最后输出
hex = x;
}
if(hex>9)
{
printf("%c", hex-10+'A');
}
else
{
printf("%c", hex+'0');
}
}

/*
将整数转换成字符串输出
*/
void int2char(int n)
{
int r = n%10;
int s = n/10;
if(s==0)
{
printf("%c" ,n+'0');
}
else
{
int2char(s);
printf("%c", r+'0');
}
}
/*
给定日期是当年的第几天
*/
int date2TotalDays(int year, int month, int day)
{
int i,totalDays=0;
int months[] = {31,28,31,30,31,30,31,30,31,30,31,30};
if((year%4==0 && year%100!=0) || year%400==0)
{
months[1] = 29;
}
for(i=0; i<month-1; i++)
{
totalDays += months[i];
}
totalDays += day;
return totalDays;
}
void main()
{
hex2dec("12cd");
printf("\n");
dec2hex(1000);
printf("\n");
int2char(483);
printf("\n");
printf("%d", date2TotalDays(2014,3,7));
}


    原文作者:进制转换
    原文地址: https://blog.csdn.net/zy3381/article/details/84535074
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞