C# Byte[] to long reverse not working

亡梦爱人 提交于 2019-12-12 01:12:37

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16752672/c-sharp-byte-to-long-reverse-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!