c# - 在 C# .Net Microframework 中将字节数组转换为 ushort 数组

标签 c# .net-micro-framework

我需要将字节数组转换为 UInt16 (ushort) 数组。我能够将字节数组转换为 UInt32 数组。

我已经看过 this SO question .但是我不能使用 BitConverter 或引用问题中给出的解决方案。

我也提到了这些问题: THISTHIS .

这是我到目前为止尝试过的。

for (uint objIndex = 0; objIndex < data.Length; ++objIndex)
{
   data[objIndex] = (Convert.ToUInt16(byteArray[objIndex * sizeof(UInt16) + 0].ToString()) << 8) 
                               + byteArray[objIndex * sizeof(UInt16) + 1]; 
   // Error - Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists.

   data[objIndex] = ((ushort)(byteArray[objIndex * sizeof(UInt16) + 0]) << 8)
                               + byteArray[objIndex + 1]; 
   // Error - Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists.
}

请让我知道这里缺少什么。

编辑: 在将每个数字转换为 ushort 后,我​​能够修复它,如下所示。

for (ushort objIndex = 0; objIndex < data.Length; ++objIndex)
{
     ushort length = sizeof(UInt16);
     data[objIndex] = (ushort)( (ushort)(byteArray[objIndex * length] << (ushort)8) +
                                                 byteArray[objIndex + 1] );
}

最佳答案

查看 Buffer.BlockCopy() .您可以将内容 (byte[]) 转储为不同的格式 (UInt16[])。

例子:

var input = byte[1024];
var output = ushort[1024 / 2]; // every ushort is 2 bytes

Buffer.BlockCopy(input, 0, output, 0, 1024);

关于c# - 在 C# .Net Microframework 中将字节数组转换为 ushort 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788061/

相关文章:

c# - 如何从 List<object> 中删除所有对象,其中 object.variable 在任何其他 object.variable2 中至少存在一次?

c# - 用常量文字初始化 ArrayList

c# - 如何将这个十六进制字符串转换成长字符串?

.net - 价格低于 300 美元的最佳 .NET Micro Framework 开发板是什么?

c# - .NET Micro Framework 的 UI 控件库

c# - using关键字的动态

c# - 如何在 EPPlus 中水平对齐居中合并单元格

c# - 使用 GC.AddMemoryPressure 触发更频繁的运行时可调用包装器 (RCW) 终结是否合适?

c# - 如何从另一个类访问winform组件?

c# - 在 ASP.NET 中使用 ItemTemplate 参数执行方法