开发者

C# int64 list to byte array and vice versa casting?

开发者 https://www.devze.com 2023-01-27 17:21 出处:网络
Please show me optimized solutions for castings: 1) public static byte[] ToBytes(List<Int64> list)

Please show me optimized solutions for castings:

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;
    }

It will be very helpful to see versions with minimized copying and/or with unsafe code (if it can be implemented). Ideally, copying of data are do not need at all.

Update:

My question is about casting like C++ manner:

__int64* ptrInt64 = (__int64*)ptrInt8;

and

__int8* ptrInt8 = (__int8*)ptrInt64

Thank you for help!!!


Edit, fixed for correct 8 byte conversion, also not terribly efficient when converting back to byte array.

    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);
    }


Use Mono.DataConvert. This library has converters to/from most primitive types, for big-endian, little-endian, and host-order byte ordering.


CLR arrays know their types and sizes so you can't just cast an array of one type to another. However, it is possible to do unsafe casting of value types. For example, here's the source to BitConverter.GetBytes(long):

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

You could write this for a list of longs, like this:

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;
}

And of course it would be easy to go in the opposite direction if this was how you wanted to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号