Question

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));
    }
}
Was it helpful?

Solution 2

The length of bytes exceed a long can hold(8 bytes, 64 bits).

For alternative solution, I'd suggest to use BigInteger if your target framework is higher than(including) .Net 4.0.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top