C#int64列表到字节数组,反之亦然?

时间:2010-11-27 04:33:43

标签: c# arrays list casting arraylist

请向我展示铸件的优化解决方案:

1)

    public static byte[] ToBytes(List<Int64> list)
    {
        byte[] bytes = null;

        //todo

        return bytes;
    }

2)

    public static List<Int64> ToList(byte[] bytes)
    {
        List<Int64> list = null;

        //todo

        return list;
    }

查看具有最小化复制和/或不安全代码的版本(如果可以实现)将非常有用。理想情况下,根本不需要复制数据。

更新

我的问题是关于像C ++一样的方式:

__int64* ptrInt64 = (__int64*)ptrInt8;

__int8* ptrInt8 = (__int8*)ptrInt64

谢谢你的帮助!!!

3 个答案:

答案 0 :(得分:2)

编辑,已修复正确的8字节转换,在转换回字节数组时效率也不高。

    public static List<Int64> ToList(byte[] bytes)
    {
        var list = new List<Int64>();
        for (int i = 0; i < bytes.Length; i += sizeof(Int64))
            list.Add(BitConverter.ToInt64(bytes, i));

        return list;
    }

    public static byte[] ToBytes(List<Int64> list)
    {
      var byteList = list.ConvertAll(new Converter<Int64, byte[]>(Int64Converter));
      List<byte> resultList = new List<byte>();

      byteList.ForEach(x => { resultList.AddRange(x); });
      return resultList.ToArray();
    }

    public static byte[] Int64Converter(Int64 x)
    {
        return BitConverter.GetBytes(x);
    }

答案 1 :(得分:1)

使用Mono.DataConvert。这个库有大多数原始类型的转换器,用于big-endian,little-endian和host-order字节排序。

答案 2 :(得分:1)

CLR数组知道它们的类型和大小,因此您不能只将一种类型的数组转换为另一种类型。但是,可以对值类型进行不安全的转换。例如,这是BitConverter.GetBytes(long)的来源:

public static unsafe byte[] GetBytes(long value)
{
    byte[] buffer = new byte[8];
    fixed (byte* numRef = buffer)
    {
        *((long*) numRef) = value;
    }
    return buffer;
}

您可以将此内容写为长片列表,如下所示:

public static unsafe byte[] GetBytes(IList<long> value)
{
    byte[] buffer = new byte[8 * value.Count];
    fixed (byte* numRef = buffer)
    {
        for (int i = 0; i < value.Count; i++)
            *((long*) (numRef + i * 8)) = value[i];
    }
    return buffer;
}

当然,如果这是你想要的方式,那么向相反的方向前进是很容易的。