[英]64-bit floating point date and time Value to DateTime C#
我有一個需要轉換為 DateTime 的 64 位浮點值。 我得到的是一個 C/Cpp 代碼塊,但我無法理解它,所以我可以在 C# 中做同樣的事情,應該感謝幫助。
我確實有這樣的信息:
日期和時間是一個 8 字節的 64 位浮點值,表示自 1900 年 1 月 1 日以來的天數。一天中的時間表示為一天的一小部分。
這是C代碼:
//Time is first 8 bytes, converted to an 8-byte float, in units of days
m1 = (unsigned int)(((((((((unsigned int)line[1]) & 0xFF)<<8) | ((unsigned int)line[2])&0xFF) << 8) | ((unsigned int)line[3])&0xFF) << 8) | ((unsigned int)line[4])&0xFF);
m2 = (unsigned int)(((((((((unsigned int)line[5]) & 0xFF)<<8) | ((unsigned int)line[6])&0xFF) << 8) | ((unsigned int)line[7])&0xFF) << 8) | ((unsigned int)line[8])&0xFF);
//Mask off mantissa bits and add back in the "hidden bit"
time = (double)((m1 & 0x000FFFFF) | 0x00100000) + ((double)m2)/thirty_two_bits;
time = time / 32.0; //Normalise by "shifting right" to complete mantissa extraction
exp = (m1 >> 20) - 0x0400 - 14; //The above calculation is good for an exponent of 14...
while (exp != 0){
if (exp < 0){
time = time / 2.0;
exp++;
}else{
time = time * 2.0;
exp--;
}
}
time = time * 3600.0 * 24.0; //Convert days to seconds
其中line
是一個字節數組,包含從索引 [1] 開始的日期和時間的 8 個字節。
對於采樣值line
是: {X, 64, 228, 8, 46, 222, 232, 221, 125, ...}
我確實嘗試了以下但沒有正確的結果:(C#):
long longvalue = BitConverter.ToInt64(line, 1);
DateTime dtm = DateTime.FromBinary(longvalue);
Hans Passant 在他對這個問題的評論中回答:
使用 MemoryStream 存儲字節,
BinaryReader.GetBytes()
從中讀取 8 個字節,Array.Reverse()
反轉字節,BitConverter.ToDouble()
將byte[]
轉換為double
,DateTime.FromOADate()
轉換為日期。 您的示例字節產生 {4/26/2012 11:09:11 AM},看起來像是一個快樂的約會。
謝謝漢斯·帕桑特。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.