문제

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));
    }
}
도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top