将uint从c移植到c#

时间:2018-05-04 14:18:31

标签: c# c porting

我正在将public void getLatestReport程序移植到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;

但在这种情况下,我遇到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;`

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

非常感谢!

1 个答案:

答案 0 :(得分:2)

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

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