C# 将任何类型的数组转换为c中长度可变的字节[]#
我试图编写一个通用方法,将任何类型的数组转换为字节数组C# 将任何类型的数组转换为c中长度可变的字节[]#,c#,arrays,bytearray,C#,Arrays,Bytearray,我试图编写一个通用方法,将任何类型的数组转换为字节数组 method definition: public byte[] convert_item_to_bytes(dynamic items) { byte[] bytearr = ?? //I tried blockcopy, but i am not getting the correct number of elements //Buffer.BlockCo
method definition:
public byte[] convert_item_to_bytes(dynamic items)
{
byte[] bytearr = ??
//I tried blockcopy, but i am not getting the correct number of elements
//Buffer.BlockCopy(items, 0, bytearr, 0, items.Length );
return bytearr;
}
examples of my method calls:
convert_item_to_bytes(new int16[]{0x1234, 0x4567, 0x9574});
convert_item_to_bytes(new int32[]{0x3545, 0x3352, 0x9642, 0x5421});
convert_item_to_bytes(new uint64[]{0x4254, 0x8468});
//etc.... my method calls can also be of float type.
我在定义中使用dynamic,因为我在运行时可以在线了解类型
PS:我看到了另一个使用BinaryFormatter和MemoryStream的示例。我不想用那个。()
有没有其他可能的方法来解决这个问题?您实际提出的问题相当多,特别是如果您不想按类型编写代码的话。幸运的是,BCL中没有那么多的数字类型,所以您可以一次将其全部写出来,甚至让它生成 下面显示了一种非常简单的方法:
public static void Main()
{
int[] intArray = new int[] { 1, 2, 42, };
byte[] intOutput = ConvertToByteArray(intArray, sizeof(int));
for (int i = 0; i < intOutput.Length; i++)
{
Console.Write("{0:x2} ", intOutput[i]);
if ((i + 1) % singleItemSize == 0)
{
Console.WriteLine();
}
}
}
private static byte[] ConvertToByteArray<T>(T[] input, int singleItemSize)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable
{
var outputArray = new byte[input.Length * singleItemSize];
// Iterate over the input array, get the bytes for each value and append them to the output array.
for (int i = 0; i < input.Length; i++)
{
var thisItemBytes = GetBytes(input[i]);
Buffer.BlockCopy(thisItemBytes, 0, outputArray, i * singleItemSize, singleItemSize);
}
return outputArray;
}
private static byte[] GetBytes<T>(T input)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable
{
if (typeof(T) == typeof(int))
{
return BitConverter.GetBytes(Convert.ToInt32(input));
}
else if (typeof(T) == typeof(float))
{
return BitConverter.GetBytes(Convert.ToSingle(input));
}
else
{
throw new ArgumentException("T");
}
}
因此,如果输入int[]{1,2,42}
,那么ConvertToByteArray()
方法将提供一个无用的12字节数组。它是无用的,因为您不知道该数组是包含12个字节、6个字符、3个整数、3个浮点数还是3个无符号整数
除此之外,所显示的代码还存在很多(性能)问题,我相信这些问题可以简化
相反,也许你可以为这个看似XY的问题找到另一个解决方案。我会研究/class。如果你知道如何将任意对象“转换”为字节数组,你可以回答这个问题。这样的前提是相当荒谬的,因为您将不得不求助于二进制序列化,这正是BinaryFormatter的用途。如果“anytype of array”实际上是指“any numeric type of array”,那么您使用的是哪个版本的C#/.Net?我询问的唯一原因是因为
ConvertToByteArray
方法上的struct
约束。我原以为这不会在C#6之前编译。@IAbstract是使用IdeOne、C#5和.NET 4.5 AFAIK编译的。我会检查(已经有一段时间了)看看我可能在struct
约束方面遇到了什么版本的问题。@IAbstract好的。据我所知,它一直有效,但请随时启发我@我会试试你的代码。我使用的是.NET4.5。我想转换为字节数组的原因是将其传输到另一个工具。那么,使用BinaryFormatter和MemoryStream是否更简单、更快?
01 00 00 00
02 00 00 00
2a 00 00 00