首页 > 解决方案 > 将 uint 从 c 移植到 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'

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

非常感谢 !

标签: c#cporting

解决方案


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

您可以使用 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。


推荐阅读