gpt4 book ai didi

c# - 将 datetime c++ 结构(以字节形式接收)转换为 c# datetime 实例

转载 作者:太空宇宙 更新时间:2023-11-04 14:15:25 33 4
gpt4 key购买 nike

所以我正在努力替换用 C++ 编写的遗留应用程序,并且在将网络通信中使用的结构映射到 C# 时遇到了一个小问题。基本上 tcp 连接的另一端使用以下结构来写入日期,我不知道如何将序列化该结构生成的字节转换为 c# 日期时间。在您到达分别由 10 位和 6 位组成的“毫秒”和“秒”之前,大部分内容都很容易,以便在它们之间共享 2 个字节。我假设您通过位移位来解决这个问题,以便将值读取和写入字节数组,但我对此没有经验。

typedef struct DATE_TIME
{
USHORT year;
UCHAR month;
UCHAR day;
UCHAR hour;
UCHAR minute;
USHORT millis : 10;
USHORT second : 6;
}

当前尝试读取的代码

ushort Year = br.ReadUInt16();
byte Month = br.ReadByte();
byte Day = br.ReadByte();
byte Hour = br.ReadByte();
byte Minute = br.ReadByte();

ushort secAndMillSec = br.ReadUInt16();
ushort Milliseconds = (ushort)(secAndMillSec >> 6);
ushort Seconds = (ushort)((ushort)(secAndMillSec << 12)>>12);

我第一次尝试写代码

 bw.Write(Year);
bw.Write(Month);
bw.Write(Day);
bw.Write(Hour);
bw.Write(Minute);

ushort secAndMillSec = (ushort)(Milliseconds << 6);
secAndMillSec = (ushort)(secAndMillSec + Seconds);
bw.Write(secAndMillSec);

它看起来对吗?到目前为止,我可以运行的所有测试数据都是空日期,所以我在测试自己时遇到了问题

最佳答案

位字段不可跨编译器移植,但我们可以假设这两个字段位于两个后续字节中。

我假设您正在接收来自网络的流,并且您正在读取日期时间。

BinaryReader reader = new BinaryReader(networkStream);
int year = reader.ReadUInt16();
int month = reader.ReadByte();
int day = reader.ReadByte();
int hour = reader.ReadByte();
int minute = reader.ReadByte();
int ms = reader.ReadUInt16();
int second = ms >> 10;
int millist = ms & 1023;
DateTime dt = new DateTime(year, month, day, hour, minute, second, millis);

关于c# - 将 datetime c++ 结构(以字节形式接收)转换为 c# datetime 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11642369/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com