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

标签 c# c++ bit-shift

所以我正在努力替换用 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/

相关文章:

c# - 重载转换运算符的转换规则

c# - 如何在 Mac 上的 Monodevelop 中将单文件程序转换为 .exe

c# - 如何在 Visual Studio 中创建测试数据库?

c - c理解的逻辑转变

c - 如果该位介于低和高之间,则将 0 位变为 1 位

我可以在 C 编程中使用乘法和除法来移位吗?

C# Enum 需要三元转换吗?

c++ - 如何将小部件保持在布局的中心

c++ - 内存泄漏, vector push_back c++

c++ - VS2010 中令人困惑的 std::string::c_str() 行为