c# - 将 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'
你能帮我解决这个问题吗?
非常感谢 !
解决方案
看起来你有很多重构要做。
您可以使用 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。
推荐阅读
- haskell - 在参数类型而不是函数类型中设置约束有什么作用?
- java - com.microsoft.azure.documentdb.DocumentClientException 日期标头不符合要求的格式
- c# - Dotnet core 3.1 和 Angular 9 的 AAD 注册
- react-native - 如何在本机反应中用父导航器中的屏幕替换当前屏幕
- html - 为什么 noUiSlider 不能在浮动步骤中工作
- c# - XamarinForms/ C# Resx.File SwitchCase
- jquery - 如何使用模态和 Jquery 将文件上传到表?
- xml - 如何将每个 URL 的值导出到不同的 XML 文件
- jquery - 将 CSS 添加到 iframe 的正文中
- mysql - 如何将数据从数据库复制到另一个数据库?