从字节数组读取/写入32位32位DateTime

时间:2018-06-01 09:31:43

标签: c#

我试图从字节数组中读取和写入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

2 个答案:

答案 0 :(得分:1)

进行位掩码和自己玩杂耍并不是非常棘手,但如果你只想使用现成的东西",我认为最简单的方法就是调用本机代码

将这两个组件读入两个using System; using System.Collections.Generic; using System.Windows.Forms; public class ExTreeView : TreeView { private const int WM_LBUTTONDBLCLK = 0x0203; protected override void WndProc(ref Message m) { if (m.Msg == WM_LBUTTONDBLCLK) { var info = this.HitTest(PointToClient(Cursor.Position)); if (info.Location == TreeViewHitTestLocations.StateImage) { m.Result = IntPtr.Zero; return; } } base.WndProc(ref m); } public IEnumerable<TreeNode> Ancestors(TreeNode node) { while (node.Parent != null) { node = node.Parent; yield return node; } } public IEnumerable<TreeNode> Descendants(TreeNode node) { foreach (TreeNode c1 in node.Nodes) { yield return c1; foreach (TreeNode c2 in Descendants(c1)) { yield return c2; } } } } ,然后拨打DosDateTimeToFileTime

private void exTreeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    if (e.Action != TreeViewAction.Unknown) {
        foreach (TreeNode x in exTreeView1.Descendants(e.Node)) {
            x.Checked = e.Node.Checked;
        }
        foreach (TreeNode x in exTreeView1.Ancestors(e.Node)) {
            bool any = false;
            foreach (TreeNode y in exTreeView1.Descendants(x))
                any = any || y.Checked;
            x.Checked = any;
        };
    }
}

答案 1 :(得分:0)

转换为16 + 16位日期/时间的结构...显然使用按位运算! : - )

Content

两个public struct DosDateTime { public ushort Date; public ushort Time; public int Year { get => ((Date >> 9) & 0x7F) + 1980; set => Date = (ushort)((Date & 0x1FF) | ((value - 1980) << 9)); } public int Month { get => (Date >> 5) & 0xF; set => Date = (ushort)((Date & 0xFE1F) | (value<< 5)); } public int Day { get => Date & 0x1F; set => Date = (ushort)((Date & 0xFFE0) | value); } public int Hour { get => (Time >> 11) & 0x1F; set => Time = (ushort)((Time & 0x7FF) | (value << 11)); } public int Minute { get => (Time >> 5) & 0x3F; set => Time = (ushort)((Time & 0xF81F) | (value << 5)); } public int Second { get => (Time & 0x1F) << 1; set => Time = (ushort)((Time & 0xFFE0) | (value >> 1)); } } ushortDate采用&#34;格式&#34;由Dos FAT Date Time结构使用(因为这是使用的格式,旧的FAT文件系统之一)。各种属性是&#34;支持&#34;通过两个Time / Date字段进行正确的按位计算。