我写了以下功能。该函数接收十六进制值的地址,例如0x4571并从十六进制值的位位置计算日,月和年。
void fat_dir_date(char *dateAr) {
const unsigned int MaskDayOfMonth = 0x1F; //0000000000011111
const unsigned int MaskMonthOfYear = 0x1E0; //0000000111100000
const unsigned int MaskYear = 0xFE00; //1111111000000000
unsigned int DayOfMonth = hex & MaskDayOfMonth; //AND Bit Operation
unsigned int MonthOfYear = hex & MaskMonthOfYear; //AND Bit Operation
MonthOfYear = MonthOfYear >> 5; //Bitshift to right position
unsigned int Year = hex & MaskYear; //AND Bit Operation
Year = Year >> 9; //Bitshift to right position
printf("%d.%d.%d", DayOfMonth, MonthOfYear, 1980+Year);
}
计算正常。我在整数DayOfMonth,MonthOfYear和Year中得到正确的数字。但是我不想用printf打印它们,而是想将值返回给调用函数。以单个值或字符串连接的最佳方式。
在C中解决这个问题的最佳方法是什么?
答案 0 :(得分:1)
你有几个选择:
struct
,并将其返回struct
,sprintf
或第一个选项是干净且易于理解。它需要一些复制,但它适用于您需要的小型结构:
struct DateTime {
int DayOfMonth;
int MonthOfYear;
int Year;
};
struct DateTime fat_dir_date(unsigned int hex) {
struct DateTime res;
res.DayOfMonth = ...
res.MonthOfYear = ...
res.Year = ...
return res;
}
答案 1 :(得分:-2)
如果您需要打印数据而不需要使用数值,我认为:
char * fat_dir_date(char *dateAr,unsigned int hex) {
const unsigned int MaskDayOfMonth = 0x1F; //0000000000011111
const unsigned int MaskMonthOfYear = 0x1E0; //0000000111100000
const unsigned int MaskYear = 0xFE00; //1111111000000000
unsigned int DayOfMonth = hex & MaskDayOfMonth; //AND Bit Operation
unsigned int MonthOfYear = hex & MaskMonthOfYear; //AND Bit Operation
MonthOfYear = MonthOfYear >> 5; //Bitshift to right position
unsigned int Year = hex & MaskYear; //AND Bit Operation
Year = Year >> 9; //Bitshift to right position
sprintf(dateAr,"%02u.%02u.%4u", DayOfMonth,MonthOfYear, 1980+Year);
return dateAr;
}
int main(void)
{
char dateAr[11];
unsigned int hex=0x1010; //Random :)
printf("%s\n" , fat_dir_date(dateAr,hex))
return 0;
}