猿问

从字节数组读取/写入 32 位 32 位日期时间

我正在尝试从字节数组中读取和写入 32 位日期时间值。我设法找到了 64 位版本。有谁知道一种简单的方法来做到这一点,但使用 32 位日期/时间?


//Go from byte array to Time/Date

long utcNowLongBack = BitConverter.ToInt64(utcNowBytes, 0);

DateTime utcNowBack = DateTime.FromBinary(utcNowLongBack);


//Create 32 bit byte array from Time/Date

DateTime utcNow = DateTime.UtcNow;

long utcNowAsLong = utcNow.ToBinary();

byte[] utcNowBytes = BitConverter.GetBytes(utcNowAsLong);

根据https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx


海绵宝宝撒
浏览 267回答 2
2回答

喵喵时光机

自己进行位掩码和杂耍并不是非常棘手,但是如果您只想“使用现成的东西”,我认为最简单的方法是调用本机代码。将两个组件一分为二UInt16,调用DosDateTimeToFileTime.[DllImport("kernel32", CallingConvention = CallingConvention.StdCall, SetLastError = true)]private static extern int DosDateTimeToFileTime(ushort dateValue, ushort timeValue, out UInt64 fileTime);public static DateTime FromDosDateTime(ushort date, ushort time){    UInt64 fileTime;    if(DosDateTimeToFileTime(date, time, out fileTime) == 0) {        throw new Exception($"Date conversion failed: {Marshal.GetLastWin32Error()}");    }    return DateTime.FromFileTime(Convert.ToInt64(fileTime));}

至尊宝的传说

一个结构来转换为/从 16 + 16 位日期/时间......显然使用按位运算!:-)public struct DosDateTime{&nbsp; &nbsp; public ushort Date;&nbsp; &nbsp; public ushort Time;&nbsp; &nbsp; public int Year&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => ((Date >> 9) & 0x7F) + 1980;&nbsp; &nbsp; &nbsp; &nbsp; set => Date = (ushort)((Date & 0x1FF) | ((value - 1980) << 9));&nbsp; &nbsp; }&nbsp; &nbsp; public int Month&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => (Date >> 5) & 0xF;&nbsp; &nbsp; &nbsp; &nbsp; set => Date = (ushort)((Date & 0xFE1F) | (value<< 5));&nbsp; &nbsp; }&nbsp; &nbsp; public int Day&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => Date & 0x1F;&nbsp; &nbsp; &nbsp; &nbsp; set => Date = (ushort)((Date & 0xFFE0) | value);&nbsp; &nbsp; }&nbsp; &nbsp; public int Hour&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => (Time >> 11) & 0x1F;&nbsp; &nbsp; &nbsp; &nbsp; set => Time = (ushort)((Time & 0x7FF) | (value << 11));&nbsp; &nbsp; }&nbsp; &nbsp; public int Minute&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => (Time >> 5) & 0x3F;&nbsp; &nbsp; &nbsp; &nbsp; set => Time = (ushort)((Time & 0xF81F) | (value << 5));&nbsp; &nbsp; }&nbsp; &nbsp; public int Second&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get => (Time & 0x1F) << 1;&nbsp; &nbsp; &nbsp; &nbsp; set => Time = (ushort)((Time & 0xFFE0) | (value >> 1));&nbsp; &nbsp; }}这两个ushort Date和Time是由DOS FAT日期时间结构中使用“格式”(因为这是使用的格式,旧的FAT文件系统的一个)。各种属性由两个Date/Time字段“支持”并进行正确的按位计算。
随时随地看视频慕课网APP
我要回答