将 uint 从 c 移植到 c#

Porting uint from c to c#

我正在将 C 程序移植到 C#

在c程序中我有这段代码

uint32_t *st = (uint32_t*)((uint8_t*)rawptr+4);
uint64_t *d = (uint64_t*)((uint8_t*)rawptr+8);
uint8_t err = st[0] >> 24;
uint8_t type = (st[0] >> 24) & 0x3;
uint32_t nybble = st[0] & 0x0ffffff;

我试着用c#转换它

uint[] st = (uint)((byte)rawptr + 4);
ulong d = (ulong)((byte)rawptr + 8);
byte err = st[0] >> 24;
byte type = (st[0] >> 24) & 0x3;
uint nybble = st[0] & 0x0ffffff;

但在这种情况下我遇到了 CS00029 错误 (Cannot convert from uint to uint[])

我也试过改成

uint st = (uint)((byte)rawptr + 4);
ulong d = (ulong)((byte)rawptr + 8);
byte err = st[0] >> 24;
byte type = (st[0] >> 24) & 0x3;
uint nybble = st[0] & 0x0ffffff;`

但在这种情况下,错误是 CS00021 Cannot apply indexing with [] to an expression of type 'uint'

你能帮我解决这个问题吗?

非常感谢!

看起来你有很多重构要做。

您可以使用 类,例如 BinaryReader 或 BitConverter。

假设 rawptr 可以转换或作为字节数组读入:(我还将其重命名为 rawBytes)

  byte[] rawBytes = new byte[DATA_LENGTH];

  UInt32 bitmaskedWord = BitConverter.ToUInt32(rawBytes, 0);
  UInt32 st = BitConverter.ToUInt32(rawBytes, 4);
  UInt32 d = BitConverter.ToUInt32(rawBytes, 8);

  bool err = (bitmaskedWord & 0xFF) != 0;
  UInt32 type = bitmaskedWord & 0x3;
  UInt32 nybble = bitmaskedWord & 0x0ffffff;

字节流可能是更好的解决方案,尤其是在rawptr 中存在不确定数据量的情况下。在这种情况下,使用 BinaryReader。