C# Byte[] to long reverse not working

Jonathan picture Jonathan · May 25, 2013 · Viewed 8.9k times · Source

Why is this program not working? I convert a byte array to long. Then from the long I convert back to a byte array. The resulting byte array is not the same as original.

class Program
{
    static void Main(string[] args)
    {
        byte[] myBytes = { 0, 0, 0, 32, 56, 99, 87, 34, 56, 56, 34, 33, 67
                         , 56, 66, 72, 1, 0, 0, 56, 0, 22};

        long data = BitConverter.ToInt64(myBytes, 0);

        byte[] byteData = BitConverter.GetBytes(data);

        Console.WriteLine("byte array: " + BitConverter.ToString(myBytes));
        Console.WriteLine("byte array: " + BitConverter.ToString(byteData));
    }
}

Answer

Soner Gönül picture Soner Gönül · May 25, 2013

Since l4V already gave the right assumption, I just want to add it as an aswer but I think my answer doesn't deserve any votes since all upvotes should go to l4V. Upvote his comment.

From BitConverter.ToInt64

The ToInt64 method converts the bytes from index startIndex to startIndex + 7 to a Int64 value.

So basicly, this conversations takes only 8 bytes (0, 0, 0, 32, 56, 99, 87, 34) of your byte array. Other bytes of your array are ignored at this situation.