2013-04-02 382 views
5

我試圖將時間結構轉換爲FAT時間戳。我的代碼如下所示:Unix時間戳到FAT時間戳

unsigned long Fat(tm_struct pTime) 
{ 
    unsigned long FatTime = 0; 

    FatTime |= (pTime.seconds/2) >> 1; 
    FatTime |= (pTime.minutes) << 5; 
    FatTime |= (pTime.hours) << 11; 
    FatTime |= (pTime.days) << 16; 
    FatTime |= (pTime.months) << 21; 
    FatTime |= (pTime.years + 20) << 25; 

    return FatTime; 
} 

是否有人擁有正確的代碼?

+0

你的問題是什麼? – 2013-04-02 11:55:13

回答

10
The DOS date/time format is a bitmask: 

       24    16     8     0 
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ 
|Y|Y|Y|Y|Y|Y|Y|M| |M|M|M|D|D|D|D|D| |h|h|h|h|h|m|m|m| |m|m|m|s|s|s|s|s| 
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ 
\___________/\________/\_________/ \________/\____________/\_________/ 
    year  month  day  hour  minute  second 

The year is stored as an offset from 1980. 
Seconds are stored in two-second increments. 
(So if the "second" value is 15, it actually represents 30 seconds.) 

我不知道你使用的是tm_struct但如果它是http://www.cplusplus.com/reference/ctime/tm/然後

unsigned long FatTime = ((pTime.tm_year - 80) << 25) | 
         (pTime.tm_mon << 21) | 
         (pTime.tm_mday << 16) | 
         (pTime.tm_hour << 11) | 
         (pTime.tm_min << 5) | 
         (pTime.tm_sec >> 1); 
+0

如果'sizeof(int)'是2(如果代碼是用於DOS實模式,則可能是這種情況),則需要使用一些類型轉換。 –

+1

順便說一句,轉換爲'unsigned'類型會更好,因爲'signed'類型的移動不是完全可移植的。 –

+0

是UTC還是本地時區的FAT時間戳? – rustyx

1

Lefterisê了幾乎正確的答案,但這裏有一個小失誤

你應該加1 tm_mon,因爲tm struct將月份保存爲從0到11(struct tm)的數字,但DOS日期/時間從1到12(FileTimeToDosDateTime)。 所以正確的是

unsigned long FatTime = ((pTime.tm_year - 80) << 25) | 
    ((pTime.tm_mon+1) << 21) | 
    (pTime.tm_mday << 16) | 
    (pTime.tm_hour << 11) | 
    (pTime.tm_min << 5) | 
    (pTime.tm_sec >> 1);